-
Notifications
You must be signed in to change notification settings - Fork 11
/
Poke.psm1
941 lines (753 loc) · 32.3 KB
/
Poke.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
###########################################
#
# POKE Toolkit 1.1
# By Oisin Grehan (MVP)
#
#
# 1.0 initial release
# 1.1 add support for out/ref parameters
#
###########################################
Set-StrictMode -Version Latest
# libraries to include
. (join-path $PSScriptRoot delegate.ps1)
# global cache for -ascustomobject instance/type proxies
# this is needed for the format helper functions as metadata
# and hints about proxied objects are hidden in ETS member
# attributes
$SCRIPT:proxyTable = @{}
############################################
#
# PS1XML Format function helper definitions
#
############################################
# used in this module (poke) for property/field filter
filter Limit-SpecialMember {
if (-not ($_.isspecialname -or $_.GetCustomAttributes([System.Runtime.CompilerServices.CompilerGeneratedAttribute], $false).count)) {
$_
} else {
if ($_.isspecialname) {
Write-Verbose "skipping special member $_"
} else {
Write-Verbose "skipping compiler generated $_"
}
}
}
function Get-Modifier {
param(
[parameter(mandatory=$true)]
[validatenotnull()]
[System.Reflection.MemberInfo]$Member
)
$modifiers = ""
try {
if ($Member.ispublic) {
$modifiers = "public"
} elseif ($Member.isFamily) {
$modifiers = "protected"
} elseif ($Member.isFamilyOrAssembly) {
$modifiers = "protected internal"
} elseif ($Member.isAssembly) {
$modifiers = "internal"
} elseif ($Member.isPrivate) {
$modifiers = "private"
}
} catch {
$modifiers = "ERROR"
}
# declared readonly?
if ($member.MemberType -eq "Field") {
$fieldInfo = [system.reflection.fieldinfo]$member
if ($fieldInfo.IsInitOnly) {
$modifiers += " readonly"
}
}
$modifiers
}
$SCRIPT:formatHelperFunctions = {
# These functions are defined within module scope for a single instance or type proxy.
$SCRIPT:adapterType = [psobject].assembly.gettype("System.Management.Automation.DotNetAdapter")
$SCRIPT:getMethodDefinition = $adapterType.getmethod("GetMethodInfoOverloadDefinition", [reflection.bindingflags]"static,nonpublic")
# cache some often used members for performance reasons
$SCRIPT:miType = [psobject].assembly.gettype("System.Management.Automation.MethodInformation")
$SCRIPT:miCtor = $mitype.GetConstructor("nonpublic,instance", $null, [type[]]@([reflection.methodinfo], [int]), $null)
$SCRIPT:miDefinition = $mitype.GetProperty("methodDefinition", [reflection.bindingflags]"instance,nonpublic")
$SCRIPT:fieldCall = $false
# workaround
if (-not $miDefinition) {
$SCRIPT:miCtor = $mitype.GetConstructor("nonpublic,instance", $null, [type[]]@([string],[reflection.methodinfo], [int]), $null)
$SCRIPT:miDefinition = $mitype.GetField("methodDefinition", [reflection.bindingflags]"instance,nonpublic")
$SCRIPT:fieldCall = $true
}
# used in dynamic modules (proxies) for method filter
filter Limit-SpecialMember {
if (-not ($_.isspecialname -or $_.GetCustomAttributes([System.Runtime.CompilerServices.CompilerGeneratedAttribute], $false).count)) {
$_
} else {
if ($_.isspecialname) {
Write-Verbose "skipping special member $_"
} else {
Write-Verbose "skipping compiler generated $_"
}
}
}
# enhanced .ctor definition with parameter names
function Get-ConstructorDefinition {
param(
[parameter(mandatory=$true)]
[type]$Type
)
$type.GetConstructors("public,nonpublic,instance") | % {
".ctor ({0})" -f (($_.getparameters() | % {
"{0} {1}" -f [microsoft.powershell.tostringcodemethods]::type($_.parametertype), $_.name
}) -join ", ")
}
}
function Get-MethodDefinition {
param(
[parameter(mandatory=$true)]
[validatenotnull()]
[reflection.methodinfo]$MethodInfo
)
# let powershell do the work
if ($SCRIPT:fieldCall) {
$mi = $miCtor.Invoke(@($methodinfo.name, $MethodInfo, 0))
$miDefinition.getvalue($mi) # field call
} else {
$mi = $miCtor.Invoke(@($MethodInfo, 0))
$miDefinition.getvalue($mi, @()) # prop call
}
}
function Get-MemberDefinition {
param(
[parameter(mandatory=$true)]
[Microsoft.PowerShell.Commands.MemberDefinition]$Member,
[parameter()]
[pstypename("Pokeable.Object")]
[psobject]$Proxy
)
# NOTE: we don't want to recursively trigger ETS so use psbase
$memberType = $member.psbase.MemberType
switch ($memberType) {
ScriptProperty {
# Property* or Field*
$baseMemberType = $member.MemberType.split(":")[0] # grab _our_ ETS value (not using psbase!)
# TODO: show {get;} or {get;set;} depending on readonly or not
# TODO: show modifiers for get/set if different; e.g. {get;private set;}
$getset = $(if ($baseMemberType -eq "Property*") { " { get; set; }" })
"{0}{1} {2}{3}" -f "", $proxy.psobject.Members[$member.Name].TypeNameOfValue, $Member.Name, $getset
}
ScriptMethod {
switch ($member.Name) {
__CreateInstance {
$baseObject = $Proxy.__GetBaseObject()
if ($baseObject -is [type]) {
(Get-ConstructorDefinition -Type $baseObject) -join ", "
} else {
(Get-ConstructorDefinition -Type $baseObject.gettype()) -join ", "
}
}
__GetBaseObject {
$baseObject = $Proxy.__GetBaseObject()
if ($baseObject -is [type]) {
"type __GetBaseObject()"
} else {
"{0} __GetBaseObject()" -f [Microsoft.PowerShell.ToStringCodeMethods]::Type($baseObject.gettype())
}
}
__GetModuleInfo {
"psmoduleinfo __GetModuleInfo()"
}
ToString {
"string ToString()"
}
default {
# retrieve from scriptmethod scriptblock attributes
$body = $proxy.psobject.members[$member.Name].script
$description = $body.Attributes.Find( { $args[0] -is [System.ComponentModel.DescriptionAttribute] })
if ($description) {
# overloads cached in description attribute above param block
$description.description
} else {
"..."
}
}
}
}
Method {
# pass through
$Member.psbase.Definition
}
Property {
# pass through
$Member.psbase.definition
}
}
}
# computes modifiers for a memberdefinition instance (public, private, internal, static etc)
function Get-MemberModifier {
param(
[parameter(mandatory=$true)]
[Microsoft.PowerShell.Commands.MemberDefinition]$Member,
[parameter()]
[pstypename("Pokeable.Object")]
[psobject]$Proxy
)
# modifiers are cached in exported function description
Write-Verbose "getting function description for $($Member.psbase.name)"
switch ($member.psbase.MemberType) {
ScriptProperty {
$getter = $proxy.psobject.members[$member.Name].getterscript
$description = $getter.Attributes.Find( { $args[0] -is [System.ComponentModel.DescriptionAttribute] })
$description.description.split(":")[1]
}
ScriptMethod {
try {
$description = (get-item function:"$($Member.psbase.name)").Description
if ($description) {
$description.split(":")[0]
} else {
# special cases
if ($member.psbase.name -eq "ToString") {
"public"
} else {
# special case proxy helpers, like __CreateInstance, __GetModuleInfo etc
"-"
}
}
} catch { "-" } # no description property on function
}
default { "public" }
}
}
# computes member type for a memberdefinition (e.g. replaces ScriptProperty with Field or Property
# and ScriptMethod with Method)
function Get-MemberType {
param(
[parameter(mandatory=$true)]
[Microsoft.PowerShell.Commands.MemberDefinition]$Member,
[parameter()]
[pstypename("Pokeable.Object")]
[psobject]$Proxy
)
# don't want to recursive trigger ETS so use psbase
$memberType = $member.psbase.MemberType
switch ($memberType) {
ScriptProperty {
# the proxied member type is cached in a description attribute on the scriptproperty's getterscript (e.g. field/property)
$getter = $proxy.psobject.members[$member.Name].getterscript
$description = $getter.Attributes.Find( { $args[0] -is [System.ComponentModel.DescriptionAttribute] })
$description.description.split(":")[0]
}
ScriptMethod {
# add asterisk to differentiate between methods on the psobject (gettype etc) and proxied members
"Method*"
}
default {
# catch all
$memberType
}
}
}
###
#
# ByRef helper
#
###
filter ConvertFrom-PSReference {
if ([ref].IsAssignableFrom($_)) {
$_.generictypearguments[0].makebyreftype()
} else {
$_
}
}
}
############################################
#
# Proxy Method generator definition (lambda)
#
############################################
$SCRIPT:initializer = {
param(
[Parameter(mandatory=$true, position=0)]
[validatenotnull()]
$baseObject,
[Parameter(mandatory=$true, position=1)]
[reflection.bindingflags]$flags,
[switch]$IncludeCompilerGenerated,
[switch]$IncludeSpecialName
)
Write-Progress -Id 1 -Activity "Peek" -Status "Initializing methods..."
write-verbose "Method initializer."
if ($baseObject.gettype().Name -eq "RuntimeType") {
# type
Write-Verbose "`$baseObject is a Type"
$methodInfos = $baseobject.getmethods($flags)| Limit-SpecialMember
$baseType = $baseObject
} else {
# instance
Write-Verbose "`$baseObject is an instance"
$methodInfos = $baseObject.GetType().getmethods($flags) | Limit-SpecialMember
$baseType = $baseObject.GetType()
}
foreach ($method in @($methodInfos|Sort-Object name -unique)) {
$methodName = $method.name
write-verbose "Creating method $methodname`(...`); building method definitions..."
$overloads = ($methodInfos|? name -eq $methodName|% { Get-MethodDefinition $_ }) -join ", "
# psscriptmethod ignores outputtype - maybe this will get fixed in later releases of ps?
# ultimately it's of dubious use for methods as overloads may differ in return type.
# of course, they must have differing parameters too as a method cannot differ _only_ by return type.
$definition = new-item function:script:$methodName -value ([scriptblock]::create("
# cache overloads in description attribute which is easily retrieved from this
# scriptblock's attributes property when emitting memberdefinition definition
[componentmodel.description('$overloads')]
param();
write-verbose 'called $methodName'
[reflection.bindingflags]`$binding = '$flags'
try {
if ((`$overloads = @(`$baseType.getmethods(`$binding)|? name -eq '$methodname')).count -gt 1) {
write-verbose 'self $self ; flags: $flags ; finding best fit overload'
`$types = [type]::gettypearray(`$args).foreach({
if (`$_.basetype -eq [ref]) {
`$_.generictypearguments[0].makebyreftype() # fix up [ref][int] to [int&]
} else { `$_ }
})
`$method = `$baseType.getmethod('$methodname', `$binding, `$null, `$types, `$null)
if (-not `$method) {
write-warning ""Could not find best fit overload for `$(`$types -join ',').""
throw
}
} else {
write-verbose 'single method; no overloads'
}
`$inargs = new-object 'object[]' `$args.length
[array]::copy(`$args, `$inargs, `$args.length)
# deref [ref] to value
for (`$i = 0; `$i -lt `$inargs.length; `$i++) {
`$elem = `$inargs[`$i]
if (`$elem -is [ref]) {
`$inargs[`$i] = `$elem.value
}
}
# invoke
write-verbose ""invoking '`$method' with: `$(`$inargs -join ',')""
`$method.invoke(`$self, `$binding, `$null, `$inargs, `$null)
# update any [ref] values in original `$args
for (`$i = 0; `$i -lt `$args.length; `$i++) {
`$elem = `$args[`$i]
if (`$elem -is [ref]) {
`$elem.value = `$inargs[`$i]
}
}
} catch {
# TODO: remove this redundant check
if (`$_.exception.innerexception -is [Reflection.TargetParameterCountException]) {
write-warning ""Could not find matching overload with `$(`$args.count) parameter(s).""
# dump overloads (public methods only?)
#`$self.'$methodname'
} else {
# error is from invocation target, rethrow
write-verbose 'rethrow on invoke'
throw
}
}")).GetNewClosure()
# isfamily: protected
# isfamilyORassembly: protected internal
# isassembly: internal
# isprivate: private
$modifiers = ""
if ($method.ispublic) {
$modifiers = "public"
} elseif ($method.isFamily) {
$modifiers = "protected"
} elseif ($method.isFamilyOrAssembly) {
$modifiers = "protected internal"
} elseif ($method.isAssembly) {
$modifiers = "internal"
} elseif ($method.isPrivate) {
$modifiers = "private"
}
$definition.description = $modifiers + ":" + $(if ($method.isstatic) { "static" } else { "" })
export-modulemember $methodname
} # /foreach method
}
############################################
#
# Type Proxy
#
############################################
function New-TypeProxy {
<#
#>
[cmdletbinding()]
param(
[parameter()]
[validatenotnullorempty()]
[string]$TypeName,
[switch]$CaseSensitive
)
$type = Find-Type $typeName `
-CaseSensitive:$CaseSensitive
if (-not $type) {
write-warning "Could not find ${typeName}. Are you sure the containing assembly has been loaded?"
return
}
# Create TypeProxy
$proxy = new-module -ascustomobject -name "Pokeable.System.RuntimeType#$($type.fullname)" {
param(
[type]$type,
[scriptblock]$initializer,
[scriptblock]$formatHelperFunctions
)
Set-StrictMode -Version latest
function apply {
param([scriptblock]$block)
. $ExecutionContext.SessionState.Module.NewBoundScriptBlock($block) @args
}
function __CreateInstance {
write-verbose "Type is $type ; `$args count is $($args.count)"
if ($type.IsAbstract) {
write-warning "Type is abstract."
return
}
$types = @()
$args|%{if($_ -eq $null){$types+=$null}else{$types+=$_.gettype()}}
write-verbose ".ctor args: length $($types.length)"
$ctor = $type.GetConstructor("Public,NonPublic,Instance", $null, $types, $null)
if (-not $ctor) {
write-warning "No matching constructor found. Available constructors:"
Get-ConstructorDefinition $type | % { write-host -ForegroundColor green " $_" }
return
}
# return wrapped object
try {
New-InstanceProxy $ctor.invoke($args) -verbose
} catch {
write-warning "Could not create instance: $_"
}
}
$self = $type
# bind format helper functions to this module's scope
. apply $formatHelperFunctions
# define methods
. apply $initializer $type "Public,NonPublic,Static,DeclaredOnly"
function __GetBaseObject {
$type
}
function __GetModuleInfo {
$ExecutionContext.SessionState.Module
}
function ToString {
"Pokeable.System.RuntimeType#$($type.fullname)"
}
export-modulemember __CreateInstance, __GetBaseObject, __GetModuleInfo, ToString
} -args $type, $initializer, $formatHelperFunctions
if ($proxy) {
$proxy.psobject.typenames.insert(0, "Pokeable.Object")
$proxy.psobject.typenames.insert(0, "Pokeable.System.RuntimeType#$($type.fullname)")
Add-fields $proxy "Public,NonPublic,DeclaredOnly,Static" > $null
Add-properties $proxy "Public,NonPublic,DeclaredOnly,Static" > $null
write-verbose "Registering in proxyTable"
$proxyTable[$proxy.tostring()] = $proxy
$proxy
}
}
############################################
#
# Instance Proxy
#
############################################
function New-InstanceProxy {
<#
#>
[cmdletbinding()]
param(
[parameter(mandatory=$true)]
[validatenotnull()]
[object]$Instance,
[switch]$IncludeInheritedMembers, # not implemented
[switch]$ExcludePublic, # not implemented
[switch]$ExcludeFields # not implemented
)
$instanceId = [guid]::NewGuid()
$type = $instance.GetType()
$proxy = new-module -ascustomobject -name "Pokeable.$($type.fullname)#$instanceId" -verbose {
param(
$self,
$instanceId,
[scriptblock]$initializer,
[scriptblock]$formatHelperFunctions
)
Set-StrictMode -Version latest
function apply {
param([scriptblock]$block)
. $ExecutionContext.SessionState.Module.NewBoundScriptBlock($block) @args
}
$type = $self.gettype()
write-verbose "Created an instance of $type"
# bind format helper functions to this module's scope
. apply $formatHelperFunctions
# define methods
. apply $initializer $self "Public,NonPublic,DeclaredOnly,Instance"
function __GetModuleInfo {
$ExecutionContext.SessionState.Module
}
function __GetBaseObject {
$self
}
function ToString() {
"Pokeable.$($type.fullname)#$instanceId"
}
export-modulemember __GetBaseObject, __GetModuleInfo, ToString
# register dispose handler on module remove
$ExecutionContext.SessionState.Module.OnRemove = {
# TODO: handle Close
if ($self.Dispose) { # -as IDisposable?
# will fail on explicit idisposable.dispose
$self.Dispose()
}
}
} -args $instance, $instanceId, $initializer, $formatHelperFunctions
if ($proxy) {
$psobject = $proxy.psobject
$psobject.typenames.insert(0, "Pokeable.Object")
$psobject.typenames.insert(0, "Pokeable.$($type.fullname)#$instanceId")
Add-fields $proxy "Public,NonPublic,DeclaredOnly,Instance" > $null
Add-properties $proxy "Public,NonPublic,DeclaredOnly,Instance" > $null
write-verbose "Registering in proxyTable"
$proxyTable[$proxy.tostring()] = $proxy
$proxy
}
}
############################################
#
# Add Fields
#
############################################
function Add-Fields {
param(
[Parameter(mandatory=$true, position=0)]
[validatenotnull()]
[pstypename("Pokeable.Object")]
$baseObject,
[Parameter(mandatory=$true, position=1)]
[reflection.bindingflags]$flags
)
Write-Progress -Id 1 -Activity "Peek" -Status "Initializing fields..."
if ($baseObject.__GetBaseObject() -is [type]) {
$type = $baseObject.__GetBaseObject()
$self = $type
} else {
$type = $baseObject.__GetBaseObject().gettype()
$self = $baseObject.__GetBaseObject()
}
$fields = $type.getfields($flags)
$psobject = $baseObject.psobject
# add fields
foreach ($field in ($fields|limit-specialmember|Sort-Object name)) {
# clean up type string for generics and accelerated types
$outputType = [Microsoft.PowerShell.ToStringCodeMethods]::type($field.FieldType)
$modifiers = Get-Modifier $field
# close over field and instance vars but insert literal for fieldtype
$getter = [scriptblock]::create(
"[componentmodel.description('Field*:$modifiers')][outputtype('$outputtype')]param(); `$field.GetValue(`$self)").GetNewClosure()
# if readonly then IsInitOnly would be flagged, but reflection can still invoke the setter so we ignore
# TODO: strongly type $value parameter in setter
$setter = { param($value); $field.SetValue($self, $value) }.GetNewClosure()
$fieldDef = New-Object management.automation.psscriptproperty $field.Name, $getter, $setter
write-verbose "Adding $flags field $($field.name) InitOnly: $($field.isinitonly)"
$psobject.properties.add($fieldDef)
}
}
############################################
#
# Add Properties
#
############################################
function Add-Properties {
param(
[Parameter(mandatory=$true, position=0)]
[validatenotnull()]
[pstypename("Pokeable.Object")]
$baseObject,
[Parameter(mandatory=$true, position=1)]
[reflection.bindingflags]$flags
)
Write-Progress -Id 1 -Activity "Peek" -Status "Initializing properties..."
if ($baseObject.__GetBaseObject() -is [type]) {
$type = $baseObject.__GetBaseObject()
$self = $type
} else {
$type = $baseObject.__GetBaseObject().gettype()
$self = $baseObject.__GetBaseObject()
}
$properties = $type.getproperties($flags)
$psobject = $baseObject.psobject
# add properties
foreach ($property in ($properties|limit-specialmember|Sort-Object name)) {
# clean up type string for generics and accelerated types
$outputType = [Microsoft.PowerShell.ToStringCodeMethods]::type($property.PropertyType)
write-verbose ("property: {0} {1} {{ ... }}" -f $outputtype, $property.name)
$getmethod = $property.GetGetMethod(<# nonpublic: #>$true) # 4.0 -- 4.5 can use GetMethod property
$setmethod = $(if ($property.CanWrite) { $property.GetSetMethod(<# nonpublic: #>$true) } else { $getmethod }) # 4.0 -- 4.5 can use SetMethod property
if ((Get-Modifier $getmethod) -eq (Get-Modifier $setmethod)) {
# readonly prop, or getter/setter have same visibility
$modifiers = Get-Modifier $getmethod
} else {
# getter/setter have different visibility
# TODO: highlight this in definition with { private get; internal set; }
$modifiers = "-"
}
# property getter
$getter = [scriptblock]::create(
"[componentmodel.description('Property*:$modifiers')][outputtype('$outputType')]param(); `$property.GetValue(`$self, @())").GetNewClosure()
#"[componentmodel.description('Property*:$modifiers')][outputtype('$outputType')]param(); if (`$value = `$property.GetValue(`$self, @())) { peek `$value }").GetNewClosure()
# I don't account for setter-only properties
if (-not $property.CanWrite) {
$propertyDef = New-Object management.automation.psscriptproperty $property.Name, $getter
} else {
# TODO: strongly type $value parameter in setter
# property setter
$setter = { param($value); $property.SetValue($self, $value, @()) }.GetNewClosure()
$propertyDef = New-Object management.automation.psscriptproperty $property.Name, $getter, $setter
}
write-verbose "Adding $flags property $($property.name)"
$psObject.properties.add($propertyDef)
}
}
############################################
#
# Find Type
#
############################################
function Find-Type {
param(
[string]$TypeName,
[reflection.bindingflags]$BindingFlags = "Public,NonPublic",
[switch]$CaseSensitive
)
write-verbose "Searching for $typeName"
$assemblies = [appdomain]::CurrentDomain.GetAssemblies()
$matches = @()
$assemblies | % {
#write-verbose "Searching $($_.getname().name)..."
$match = $_.gettype($typename, $false, !$CaseSensitive)
if ($match) {
$matches += $match
}
}
write-verbose "Found $($matches.length) match(es)."
$matches
}
############################################
#
# New Object Proxy (peek)
#
############################################
function New-ObjectProxy {
<#
.SYNOPSIS
Return a type or instance proxy of a managed type
.DESCRIPTION
Return a type or instance proxy of a managed type, exposing all non-public fields, properties and methods.
Methods can be invoked, fields written to and private properties set. To see modifiers and method definitions
use the standard command of Get-Member. Use the following meta-methods to work with proxies:
* __CreateInstance() Create an instance of a proxied System.Type.
* __GetBaseObject() Get the proxied System.Type or instance.
.PARAMETER InputObject
Accepts a Type or instance from the pipeline. Can also accept input as the first positional parameter.
.PARAMETER Name
Accepts the name of a Type to proxy, e.g. system.text.stringbuilder.
.PARAMETER CaseSensitive
Used in conjunction with -Name to specific a case-sensitive type name.
.EXAMPLE
$ise = peek $psise
$ise | get-member
Get a live instance of the ISE's $psise global, and examine and manipulate its internal structures.
.EXAMPLE
$job = start-job { 42 } | peek
$job | gm
Get an instance of psremotingjob and view all private, internal, protected and public members.
.EXAMPLE
$throttlemanager = peek (start-job { 42 } | peek).throttlemanager
$throttlemanager.ThrottleLimit = 64
Get an instance of a job's internal throttle manager and increse the throttle limit from 32 to 64.
#>
[cmdletbinding(defaultparametersetname="inputobject")]
param(
[parameter(position=0, mandatory=$true, parametersetname="typeName")]
[validatenotnullorempty()]
[string]$Name,
[parameter(parametersetname="typeName")]
[switch]$CaseSensitive,
[parameter(valuefrompipeline=$true, parametersetname="inputobject", position="0")]
[validatenotnull()]
$InputObject
)
if ($PSCmdlet.ParameterSetName -eq "inputobject") {
if ($InputObject -is [type]) {
New-TypeProxy -TypeName $InputObject.fullname -CaseSensitive
} else {
New-InstanceProxy -Instance $InputObject
}
} else {
New-TypeProxy -TypeName $Name -CaseSensitive:$CaseSensitive
}
Write-Progress -id 1 -Activity "Poke" -Completed
}
<#
Update-TypeData -Force -TypeName System.Management.Automation.PSMethod -MemberType ScriptMethod -MemberName CreateDelegate -Value {
param(
[parameter(position=0, mandatory=$true)]
[validatenotnull()]
[validatescript({ ([delegate].isassignablefrom($_)) })]
[type]$DelegateType
)
$this | Get-Delegate -Delegate $DelegateType
}
#>
function Invoke-FormatHelper {
param(
[parameter()]
[Microsoft.PowerShell.Commands.MemberDefinition]$Member,
[parameter()]
[string]$CommandName,
[parameter()]
[string]$DefaultValue
)
$proxy = $proxyTable[$Member.TypeName]
if ($proxy) {
try {
# invoke the command in the scope of the module that proxies this type or instance
& $proxyTable[$Member.TypeName].__GetModuleInfo() $CommandName $Member $proxy @args
} catch {
write-warning $_
$DefaultValue
}
} else {
# not a proxied type or instance
$DefaultValue
}
}
#update-formatdata -PrependPath (join-path $ExecutionContext.SessionState.Module.ModuleBase 'Poke.Format.ps1xml')
# scriptblock is not bound to this module's scope? weird bug? we have to use invoke-format helper to lookup module in a shared global
Update-TypeData -typename Microsoft.PowerShell.Commands.MemberDefinition -MemberType ScriptProperty -MemberName MemberType -Value {
try { invoke-formathelper $this get-membertype -default $this.psbase.membertype } catch { write-warning "get-membertype: $_" }
} -Force
Update-TypeData -typename Microsoft.PowerShell.Commands.MemberDefinition -MemberType ScriptProperty -MemberName Modifier -Value {
try { invoke-formathelper $this get-membermodifier -default "public" } catch { write-warning "get-membermodifier: $_" }
} -Force
# overloads
Update-TypeData -typename Microsoft.PowerShell.Commands.MemberDefinition -MemberType ScriptProperty -MemberName Definition -Value {
try { invoke-formathelper $this get-memberdefinition -default $this.psbase.definition } catch { write-warning "get-memberdefinition: $_" }
} -Force
# shortcut for $o | peek | gm
function Get-PokeMember { $args | peek | Get-Member }
$ExecutionContext.SessionState.Module.OnRemove = {
remove-module poke_init -ErrorAction SilentlyContinue
}
#
# Exports
#
new-alias -Name peek -Value New-ObjectProxy -Force
Export-ModuleMember -Alias peek -Function New-ObjectProxy, New-TypeProxy, New-InstanceProxy, Get-Delegate, Invoke-FormatHelper, Get-PokeMember