forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplicit.Remoting.Tests.ps1
More file actions
2078 lines (1670 loc) · 80.5 KB
/
Copy pathImplicit.Remoting.Tests.ps1
File metadata and controls
2078 lines (1670 loc) · 80.5 KB
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Describe "Implicit remoting and CIM cmdlets with AllSigned and Restricted policy" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines
$skipTest = !$IsWindows
if ($skipTest) { return }
#
# GET CERTIFICATE
#
$tempName = "$env:TEMP\signedscript_$(Get-Random).ps1"
"123456" > $tempName
$cert = $null
foreach ($thisCertificate in (Get-ChildItem cert:\ -rec -codesigning))
{
$null = Set-AuthenticodeSignature $tempName -Certificate $thisCertificate
if ((Get-AuthenticodeSignature $tempName).Status -eq "Valid")
{
$cert = $thisCertificate
break
}
}
# Skip the tests if we couldn't find a code sign certificate
# This will happen in NanoServer and IoT
if ($cert -eq $null)
{
$skipTest = $true
return
}
# Ensure the cert is trusted
if (-not (Test-Path "cert:\currentuser\TrustedPublisher\$($cert.Thumbprint)"))
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store "TrustedPublisher"
$store.Open("ReadWrite")
$store.Add($cert)
$store.Close()
}
#
# Set process scope execution policy to 'AllSigned'
#
$oldExecutionPolicy = Get-ExecutionPolicy -Scope Process
Set-ExecutionPolicy AllSigned -Scope Process
#
# Create a remote session
#
$session = New-RemoteSession
}
AfterAll {
if ($skipTest) { return }
if ($tempName -ne $null) { Remove-Item -Path $tempName -Force -ErrorAction SilentlyContinue }
if ($oldExecutionPolicy -ne $null) { Set-ExecutionPolicy $oldExecutionPolicy -Scope Process }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
#
# TEST - Verifying that Import-PSSession signs the files
#
It "Verifies that Import-PSSession works in AllSigned if Certificate is used" -Skip:$skipTest {
try {
$importedModule = Import-PSSession $session Get-Variable -Prefix Remote -Certificate $cert -AllowClobber
$importedModule | Should Not Be $null
} finally {
$importedModule | Remove-Module -Force -ErrorAction SilentlyContinue
}
}
It "Verifies security error when Certificate parameter is not used" -Skip:$skipTest {
try {
$importedModule = Import-PSSession $session Get-Variable -Prefix Remote -AllowClobber
throw "expect Import-PSSession to throw"
} catch {
$_.FullyQualifiedErrorId | Should Be "InvalidOperation,Microsoft.PowerShell.Commands.ImportPSSessionCommand"
}
}
}
Describe "Tests Import-PSSession cmdlet works with types unavailable on the client" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines for now
$skipTest = !$IsWindows
if ($skipTest) { return }
$typeDefinition = @"
namespace MyTest
{
public enum MyEnum
{
Value1 = 1,
Value2 = 2
}
}
"@
#
# Create a remote session
#
$session = New-RemoteSession
Invoke-Command -Session $session -Script { Add-Type -TypeDefinition $args[0] } -Args $typeDefinition
Invoke-Command -Session $session -Script { function foo { param([MyTest.MyEnum][Parameter(Mandatory = $true)]$x) $x } }
}
AfterAll {
if ($skipTest) { return }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
It "Verifies client-side unavailable enum is correctly handled" -Skip:$skipTest {
try {
$module = Import-PSSession -Session $session -CommandName foo -AllowClobber
# The enum is treated as an int
(foo -x "Value2") | Should Be 2
# The enum is to-string-ed appropriately
(foo -x "Value2").ToString() | Should Be "Value2"
} finally {
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
}
}
Describe "Cmdlet help from remote session" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines for now
$skipTest = !$IsWindows
if ($skipTest) { return }
$session = New-RemoteSession
}
AfterAll {
if ($skipTest) { return }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
It "Verifies that get-help name for remote proxied commands matches the get-command name" -Skip:$skipTest {
try {
$module = Import-PSSession $session -Name Select-Object -prefix My -AllowClobber
$gcmOutPut = (Get-Command Select-MyObject ).Name
$getHelpOutPut = (Get-Help Select-MyObject).Name
$gcmOutPut | Should Be $getHelpOutPut
} finally {
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
}
}
Describe "Import-PSSession Cmdlet error handling" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines for now
$skipTest = !$IsWindows
if ($skipTest) { return }
$session = New-RemoteSession
}
AfterAll {
if ($skipTest) { return }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
It "Verifies that broken alias results in one error" -Skip:$skipTest {
try {
Invoke-Command $session { Set-Alias BrokenAlias NonExistantCommand }
$module = Import-PSSession $session -CommandName:BrokenAlias -CommandType:All -ErrorAction SilentlyContinue -ErrorVariable expectedError -AllowClobber
$expectedError | Should Not Be NullOrEmpty
$expectedError[0].ToString().Contains("BrokenAlias") | Should Be $true
} finally {
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
Invoke-Command $session { Remove-Item alias:BrokenAlias }
}
}
Context "Test content and format of proxied error message (Windows 7: #319080)" {
BeforeAll {
if ($skipTest) { return }
$module = Import-PSSession -Session $session -Name Get-Variable -Prefix My -AllowClobber
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Test non-terminating error" -Skip:$skipTest {
$results = Get-MyVariable blah,pid 2>&1
($results[1]).Value | Should Not Be $PID # Verifies that returned PID is not for this session
$errorString = $results[0] | Out-String # Verifies error message for variable blah
($errorString -like "*VariableNotFound*") | Should Be $true
}
It "Test terminating error" -Skip:$skipTest {
$results = Get-MyVariable pid -Scope blah 2>&1
$results.Count | Should Be 1 # Verifies that remote session pid is not returned
$errorString = $results[0] | Out-String # Verifes error message for incorrect Scope parameter argument
($errorString -like "*Argument*") | Should Be $true
}
}
Context "Ordering of a sequence of error and output messages (Windows 7: #405065)" {
BeforeAll {
if ($skipTest) { return }
Invoke-Command $session { function foo1{1; write-error 2; 3; write-error 4; 5; write-error 6} }
$module = Import-PSSession $session -CommandName foo1 -AllowClobber
$icmErr = $($icmOut = Invoke-Command $session { foo1 }) 2>&1
$proxiedErr = $($proxiedOut = foo1) 2>&1
$proxiedOut2 = foo1 2>$null
$icmOut = "$icmOut"
$icmErr = "$icmErr"
$proxiedOut = "$proxiedOut"
$proxiedOut2 = "$proxiedOut2"
$proxiedErr = "$proxiedErr"
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Verifies proxied output = proxied output 2" -Skip:$skipTest {
$proxiedOut2 | Should Be $proxiedOut
}
It "Verifies proxied output = icm output (for mixed error and output results)" -Skip:$skipTest {
$icmOut | Should Be $proxiedOut
}
It "Verifies proxied error = icm error (for mixed error and output results)" -Skip:$skipTest {
$icmErr | Should Be $proxiedErr
}
It "Verifies proxied order = icm order (for mixed error and output results)" -Skip:$skipTest {
$icmOrder = Invoke-Command $session { foo1 } 2>&1 | out-string
$proxiedOrder = foo1 2>&1 | out-string
$icmOrder | Should Be $proxiedOrder
}
}
Context "WarningVariable parameter works with implicit remoting (Windows 8: #44861)" {
BeforeAll {
if ($skipTest) { return }
$module = Import-PSSession $session -CommandName Write-Warning -Prefix Remote -AllowClobber
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Verifies WarningVariable" -Skip:$skipTest {
$global:myWarningVariable = @()
Write-RemoteWarning MyWarning -WarningVariable global:myWarningVariable
([string]($myWarningVariable[0])) | Should Be 'MyWarning'
}
}
}
Describe "Tests Export-PSSession" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines for now
$skipTest = !$IsWindows
if ($skipTest) { return }
$sessionOption = New-PSSessionOption -ApplicationArguments @{myTest="MyValue"}
$session = New-RemoteSession -SessionOption $sessionOption
$file = [IO.Path]::Combine([IO.Path]::GetTempPath(), [Guid]::NewGuid().ToString())
$results = Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file
$oldTimestamp = $($results | Select -First 1).LastWriteTime
}
AfterAll {
if ($skipTest) { return }
if ($file -ne $null) { Remove-Item $file -Force -Recurse -ErrorAction SilentlyContinue }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
It "Verifies Export-PSSession creates a file/directory" -Skip:$skipTest {
@(Get-Item $file).Count | Should Be 1
}
It "Verifies Export-PSSession creates a psd1 file" -Skip:$skipTest {
($results | ?{ $_.Name -like "*$(Split-Path -Leaf $file).psd1" }) | Should Be $true
}
It "Verifies Export-PSSession creates a psm1 file" -Skip:$skipTest {
($results | ?{ $_.Name -like "*.psm1" }) | Should Be $true
}
It "Verifies Export-PSSession creates a ps1xml file" -Skip:$skipTest {
($results | ?{ $_.Name -like "*.ps1xml" }) | Should Be $true
}
It "Verifies that Export-PSSession fails when a module directory already exists" -Skip:$skipTest {
try {
Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file -EA SilentlyContinue -ErrorVariable expectedError
} catch { }
$expectedError | Should Not Be NullOrEmpty
# Error contains reference to the directory that already exists
([string]($expectedError[0]) -like "*$file*") | Should Be $true
}
It "Verifies that overwriting an existing directory succeeds with -Force" -Skip:$skipTest {
$newResults = Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file -Force
# Verifies that Export-PSSession returns 4 files
@($newResults).Count | Should Be 4
# Verifies that Export-PSSession creates *new* files
$newResults | % { $_.LastWriteTime | Should BeGreaterThan $oldTimestamp }
}
Context "The module is usable when the original runspace is still around" {
BeforeAll {
if ($skipTest) { return }
$module = Import-Module $file -PassThru
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Verifies that proxy returns remote pid" -Skip:$skipTest {
(Get-Variable -Name pid).Value | Should Not Be $pid
}
It "Verfies Remove-Module doesn't remove user's runspace" -Skip:$skipTest {
Remove-Module $module -Force -ErrorAction SilentlyContinue
(Get-PSSession -InstanceId $session.InstanceId) | Should Not Be NullOrEmpty
}
}
}
Describe "Proxy module is usable when the original runspace is no longer around" -tags "Feature" {
BeforeAll {
# Run the tests only in FullCLR powershell because implicit credential doesn't work in AppVeyor builder
$skipTest = !$IsWindows -or $IsCoreCLR
if ($skipTest) { return }
$sessionOption = New-PSSessionOption -ApplicationArguments @{myTest="MyValue"}
$session = New-RemoteSession -SessionOption $sessionOption
$file = [IO.Path]::Combine([IO.Path]::GetTempPath(), [Guid]::NewGuid().ToString())
$null = Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file
# Close the session to test the behavior of proxy module
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue; $session = $null }
}
AfterAll {
if ($skipTest) { return }
if ($file -ne $null) { Remove-Item $file -Force -Recurse -ErrorAction SilentlyContinue }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
## It requires 'New-PSSession' to work with implicit credential to allow proxied command to create new session.
## Implicit credential doesn't work in AppVeyor builder, so mark all tests here '-pending'.
Context "Proxy module should create a new session" {
BeforeAll {
if ($skipTest) { return }
$module = import-Module $file -PassThru -Force
$internalSession = & $module { $script:PSSession }
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Verifies proxy should return remote pid" -Pending {
(Get-Variable -Name PID).Value | Should Not Be $PID
}
It "Verifies ApplicationArguments got preserved correctly" -Pending {
$(Invoke-Command $internalSession { $PSSenderInfo.ApplicationArguments.MyTest }) | Should Be "MyValue"
}
It "Verifies Remove-Module removed the runspace that was automatically created" -Pending {
Remove-Module $module -Force
((Get-PSSession -InstanceId $internalSession.InstanceId -ErrorAction SilentlyContinue) -eq $null) | Should Be $true
}
It "Verifies Runspace is closed after removing module from Export-PSSession that got initialized with an internal r-space" -Pending {
($internalSession.Runspace.RunspaceStateInfo.ToString()) | Should Be "Closed"
}
}
Context "Runspace created by the module with explicit session options" {
BeforeAll {
if ($skipTest) { return }
$explicitSessionOption = New-PSSessionOption -Culture fr-FR -UICulture de-DE
$module = import-Module $file -PassThru -Force -ArgumentList $null, $explicitSessionOption
$internalSession = & $module { $script:PSSession }
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Verifies proxy should return remote pid" -Pending {
(Get-Variable -Name PID).Value | Should Not Be $PID
}
# culture settings should be taken from the explicitly passed session options
It "Verifies proxy returns modified culture" -Pending {
(Get-Variable -Name PSCulture).Value | Should Be "fr-FR"
}
It "Verifies proxy returns modified culture" -Pending {
(Get-Variable -Name PSUICulture).Value | Should Be "de-DE"
}
# removing the module should remove the implicitly/magically created runspace
It "Verifies Remove-Module removes automatically created runspace" -Pending {
Remove-Module $module -Force
((Get-PSSession -InstanceId $internalSession.InstanceId -ErrorAction SilentlyContinue) -eq $null) | Should Be $true
}
It "Verifies Runspace is closed after removing module from Export-PSSession that got initialized with an internal r-space" -Pending {
($internalSession.Runspace.RunspaceStateInfo.ToString()) | Should Be "Closed"
}
}
Context "Passing a runspace into proxy module" {
BeforeAll {
if ($skipTest) { return }
$newSession = New-RemoteSession
$module = import-Module $file -PassThru -Force -ArgumentList $newSession
$internalSession = & $module { $script:PSSession }
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
if ($newSession -ne $null) { Remove-PSSession $newSession -ErrorAction SilentlyContinue }
}
It "Verifies proxy returns remote pid" -Pending {
(Get-Variable -Name PID).Value | Should Not Be $PID
}
It "Verifies switch parameters work" -Pending {
(Get-Variable -Name PID -ValueOnly) | Should Not Be $PID
}
It "Verifies Adding a module affects runspace's state" -Pending {
($internalSession.Runspace.RunspaceStateInfo.ToString()) | Should Be "Opened"
}
It "Verifies Runspace stays opened after removing module from Export-PSSession that got initialized with an external runspace" -Pending {
Remove-Module $module -Force
($internalSession.Runspace.RunspaceStateInfo.ToString()) | Should Be "Opened"
}
}
}
Describe "Import-PSSession with FormatAndTypes" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines for now
$skipTest = !$IsWindows
if ($skipTest) { return }
$session = New-RemoteSession
function CreateTempPs1xmlFile
{
do {
$tmpFile = [IO.Path]::Combine([IO.Path]::GetTempPath(), [IO.Path]::GetRandomFileName()) + ".ps1xml";
} while ([IO.File]::Exists($tmpFile))
$tmpFile
}
function CreateTypeFile {
$tmpFile = CreateTempPs1xmlFile
@"
<Types>
<Type>
<Name>System.Management.Automation.Host.Coordinates</Name>
<Members>
<NoteProperty>
<Name>MyTestLabel</Name>
<Value>123</Value>
</NoteProperty>
</Members>
</Type>
<Type>
<Name>MyTest.Root</Name>
<Members>
<MemberSet>
<Name>PSStandardMembers</Name>
<Members>
<NoteProperty>
<Name>SerializationDepth</Name>
<Value>1</Value>
</NoteProperty>
</Members>
</MemberSet>
</Members>
</Type>
<Type>
<Name>MyTest.Son</Name>
<Members>
<MemberSet>
<Name>PSStandardMembers</Name>
<Members>
<NoteProperty>
<Name>SerializationDepth</Name>
<Value>1</Value>
</NoteProperty>
</Members>
</MemberSet>
</Members>
</Type>
<Type>
<Name>MyTest.Grandson</Name>
<Members>
<MemberSet>
<Name>PSStandardMembers</Name>
<Members>
<NoteProperty>
<Name>SerializationDepth</Name>
<Value>1</Value>
</NoteProperty>
</Members>
</MemberSet>
</Members>
</Type>
</Types>
"@ | set-content $tmpFile
$tmpFile
}
function CreateFormatFile {
$tmpFile = CreateTempPs1xmlFile
@"
<Configuration>
<ViewDefinitions>
<View>
<Name>MySizeView</Name>
<ViewSelectedBy>
<TypeName>System.Management.Automation.Host.Size</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>MyTestWidth</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>MyTestHeight</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Width</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Height</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
"@ | set-content $tmpFile
$tmpFile
}
$formatFile = CreateFormatFile
$typeFile = CreateTypeFile
}
AfterAll {
if ($skipTest) { return }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
if ($formatFile -ne $null) { Remove-Item $formatFile -Force -ErrorAction SilentlyContinue }
if ($typeFile -ne $null) { Remove-Item $typeFile -Force -ErrorAction SilentlyContinue }
}
Context "Importing format file works" {
BeforeAll {
if ($skipTest) { return }
$formattingScript = { new-object System.Management.Automation.Host.Size | %{ $_.Width = 123; $_.Height = 456; $_ } | Out-String }
$originalLocalFormatting = & $formattingScript
# Original local and remote formatting should be equal (sanity check)
$originalRemoteFormatting = Invoke-Command $session $formattingScript
$originalLocalFormatting | Should Be $originalRemoteFormatting
Invoke-Command $session { param($file) Update-FormatData $file } -ArgumentList $formatFile
# Original remote and modified remote formatting should not be equal (sanity check)
$modifiedRemoteFormatting = Invoke-Command $session $formattingScript
$originalRemoteFormatting | Should Not Be $modifiedRemoteFormatting
$module = Import-PSSession -Session $session -CommandName @() -FormatTypeName * -AllowClobber
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "modified remote and imported local should be equal" -Skip:$skipTest {
$importedLocalFormatting = & $formattingScript
$modifiedRemoteFormatting | Should Be $importedLocalFormatting
}
It "original local and unimported local should be equal" -Skip:$skipTest {
Remove-Module $module -Force
$unimportedLocalFormatting = & $formattingScript
$originalLocalFormatting | Should Be $unimportedLocalFormatting
}
}
It "Updating type table in a middle of a command has effect on serializer" -Skip:$skipTest {
$results = Invoke-Command $session -ArgumentList $typeFile -ScriptBlock {
param($file)
New-Object System.Management.Automation.Host.Coordinates
Update-TypeData $file
New-Object System.Management.Automation.Host.Coordinates
}
# Should get 2 deserialized S.M.A.H.Coordinates objects
$results.Count | Should Be 2
# First object shouldn't have the additional ETS note property
$results[0].MyTestLabel -eq $null | Should Be $true
# Second object should have the additional ETS note property
$results[1].MyTestLabel | Should Be 123
}
Context "Implicit remoting works even when types.ps1xml is missing on the client" {
BeforeAll {
if ($skipTest) { return }
$typeDefinition = @"
namespace MyTest
{
public class Root
{
public Root(string s) { text = s; }
public Son Son = new Son();
public string text;
}
public class Son
{
public Grandson Grandson = new Grandson();
}
public class Grandson
{
public string text = "Grandson";
}
}
"@
Invoke-Command -Session $session -Script { Add-Type -TypeDefinition $args[0] } -ArgumentList $typeDefinition
Invoke-Command -Session $session -Script { function foo { New-Object MyTest.Root "root" } }
Invoke-Command -Session $session -Script { function bar { param([Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]$Son) $Son.Grandson.text } }
$module = import-pssession $session foo,bar -AllowClobber
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Serialization works for top-level properties" -Skip:$skipTest {
$x = foo
$x.text | Should Be "root"
}
It "Serialization settings works for deep properties" -Skip:$skipTest {
$x = foo
$x.Son.Grandson.text | Should Be "Grandson"
}
It "Serialization settings are preserved even if types.ps1xml is missing on the client" -Skip:$skipTest {
$y = foo | bar
$y | Should Be "Grandson"
}
}
}
Describe "Import-PSSession functional tests" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines for now
$skipTest = !$IsWindows
if ($skipTest) { return }
$session = New-RemoteSession
# Define a remote function
Invoke-Command -Session $session { function MyFunction { param($x) "x = '$x'; args = '$args'" } }
# Define a remote proxy script cmdlet
$remoteCommandType = $ExecutionContext.InvokeCommand.GetCommand('Get-Variable', [System.Management.Automation.CommandTypes]::Cmdlet)
$remoteProxyBody = [System.Management.Automation.ProxyCommand]::Create($remoteCommandType)
$remoteProxyDeclaration = "function Get-VariableProxy { $remoteProxyBody }"
Invoke-Command -Session $session { param($x) Invoke-Expression $x } -Arg $remoteProxyDeclaration
$remoteAliasDeclaration = "set-alias gvalias Get-Variable"
Invoke-Command -Session $session { param($x) Invoke-Expression $x } -Arg $remoteAliasDeclaration
Remove-Item alias:gvalias -Force -ErrorAction silentlycontinue
# Import a remote function, script cmdlet, cmdlet, native application, alias
$module = Import-PSSession -Session $session -Name MyFunction,Get-VariableProxy,Get-Variable,gvalias,cmd -AllowClobber -Type All
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
It "Import-PSSession should return a PSModuleInfo object" -Skip:$skipTest {
$module | Should Not Be NullOrEmpty
}
It "Import-PSSession should return a PSModuleInfo object" -Skip:$skipTest {
($module -as [System.Management.Automation.PSModuleInfo]) | Should Not Be NullOrEmpty
}
It "Helper functions should not be imported" -Skip:$skipTest {
((Get-Item function:*PSImplicitRemoting* -ErrorAction SilentlyContinue) -eq $null) | Should Be $true
}
It "Calls implicit remoting proxies 'MyFunction'" -Skip:$skipTest {
(MyFunction 1 2 3) | Should Be "x = '1'; args = '2 3'"
}
It "proxy should return remote pid" -Skip:$skipTest {
(Get-VariableProxy -Name:pid).Value | Should Not Be $pid
}
It "proxy should return remote pid" -Skip:$skipTest {
(Get-Variable -Name:pid).Value | Should Not Be $pid
}
It "proxy should return remote pid" -Skip:$skipTest {
$(& (Get-Command gvalias -Type alias) -Name:pid).Value | Should Not Be $pid
}
It "NoName-c8aeb5c8-2388-4d64-98c1-a9c6c218d404" -Skip:$skipTest {
Invoke-Command -Session $session { $env:TestImplicitRemotingVariable = 123 }
(cmd.exe /c "echo TestImplicitRemotingVariable=%TestImplicitRemotingVariable%") | Should Be "TestImplicitRemotingVariable=123"
}
Context "Test what happens after the runspace is closed" {
BeforeAll {
if ($skipTest) { return }
Remove-PSSession $session
# The loop below works around the fact that PSEventManager uses threadpool worker to queue event handler actions to process later.
# Usage of threadpool means that it is impossible to predict when the event handler will run (this is Windows 8 Bugs: #882977).
$i = 0
while ( ($i -lt 20) -and ($null -ne (Get-Module | ? { $_.Path -eq $module.Path })) )
{
$i++
Start-Sleep -Milliseconds 50
}
}
It "Temporary module should be automatically removed after runspace is closed" -Skip:$skipTest {
((Get-Module | ? { $_.Path -eq $module.Path }) -eq $null) | Should Be $true
}
It "Temporary psm1 file should be automatically removed after runspace is closed" -Skip:$skipTest {
((Get-Item $module.Path -ErrorAction SilentlyContinue) -eq $null) | Should Be $true
}
It "Event should be unregistered when the runspace is closed" -Skip:$skipTest {
# Check that the implicit remoting event has been removed.
$implicitEventCount = 0
foreach ($item in $ExecutionContext.Events.Subscribers)
{
if ($item.SourceIdentifier -match "Implicit remoting event") { $implicitEventCount++ }
}
$implicitEventCount | Should Be 0
}
It "Private functions from the implicit remoting module shouldn't get imported into global scope" -Skip:$skipTest {
@(Get-ChildItem function:*Implicit* -ErrorAction SilentlyContinue).Count | Should Be 0
}
}
}
Describe "Implicit remoting parameter binding" -tags "Feature" {
BeforeAll {
# Skip test for non-windows machines for now
$skipTest = !$IsWindows
if ($skipTest) { return }
$session = New-RemoteSession
}
AfterAll {
if ($skipTest) { return }
if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue }
}
It "Binding of ValueFromPipeline should work" -Skip:$skipTest {
try {
$module = Import-PSSession -Session $session -Name Get-Random -AllowClobber
$x = 1..20 | Get-Random -Count 5
$x.Count | Should Be 5
} finally {
Remove-Module $module -Force
}
}
Context "Pipeline-based parameter binding works even when client has no type constraints (Windows 7: #391157)" {
BeforeAll {
if ($skipTest) { return }
Invoke-Command -Session $session -ScriptBlock {
function foo {
[cmdletbinding(defaultparametersetname="string")]
param(
[string]
[parameter(ParameterSetName="string", ValueFromPipeline = $true)]
$string,
[ipaddress]
[parameter(ParameterSetName="ipaddress", ValueFromPipeline = $true)]
$ipaddress
)
"Bound parameter: $($myInvocation.BoundParameters.Keys | sort)"
}
}
# Sanity checks.
Invoke-Command $session {"s" | foo} | Should Be "Bound parameter: string"
Invoke-Command $session {[ipaddress]::parse("127.0.0.1") | foo} | Should Be "Bound parameter: ipaddress"
$module = Import-PSSession $session foo -AllowClobber
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Pipeline binding works even if it relies on type constraints" -Skip:$skipTest {
("s" | foo) | Should Be "Bound parameter: string"
}
It "Pipeline binding works even if it relies on type constraints" -Skip:$skipTest {
([ipaddress]::parse("127.0.0.1") | foo) | Should Be "Bound parameter: ipaddress"
}
}
Context "Pipeline-based parameter binding works even when client has no type constraints and parameterset is ambiguous (Windows 7: #430379)" {
BeforeAll {
if ($skipTest) { return }
Invoke-Command -Session $session -ScriptBlock {
function foo {
param(
[string]
[parameter(ParameterSetName="string", ValueFromPipeline = $true)]
$string,
[ipaddress]
[parameter(ParameterSetName="ipaddress", ValueFromPipeline = $true)]
$ipaddress
)
"Bound parameter: $($myInvocation.BoundParameters.Keys)"
}
}
# Sanity checks.
Invoke-Command $session {"s" | foo} | Should Be "Bound parameter: string"
Invoke-Command $session {[ipaddress]::parse("127.0.0.1") | foo} | Should Be "Bound parameter: ipaddress"
$module = Import-PSSession $session foo -AllowClobber
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Pipeline binding works even if it relies on type constraints and parameter set is ambiguous" -Skip:$skipTest {
("s" | foo) | Should Be "Bound parameter: string"
}
It "Pipeline binding works even if it relies on type constraints and parameter set is ambiguous" -Skip:$skipTest {
([ipaddress]::parse("127.0.0.1") | foo) | Should Be "Bound parameter: ipaddress"
}
}
Context "pipeline-based parameter binding works even when one of parameters that can be bound by pipeline gets bound by name" {
BeforeAll {
if ($skipTest) { return }
Invoke-Command -Session $session -ScriptBlock {
function foo {
param(
[DateTime]
[parameter(ValueFromPipeline = $true)]
$date,
[ipaddress]
[parameter(ValueFromPipeline = $true)]
$ipaddress
)
"Bound parameter: $($myInvocation.BoundParameters.Keys | sort)"
}
}
# Sanity checks.
Invoke-Command $session {Get-Date | foo} | Should Be "Bound parameter: date"
Invoke-Command $session {[ipaddress]::parse("127.0.0.1") | foo} | Should Be "Bound parameter: ipaddress"
Invoke-Command $session {[ipaddress]::parse("127.0.0.1") | foo -date (get-date)} | Should Be "Bound parameter: date ipaddress"
Invoke-Command $session {Get-Date | foo -ipaddress ([ipaddress]::parse("127.0.0.1"))} | Should Be "Bound parameter: date ipaddress"
$module = Import-PSSession $session foo -AllowClobber
}
AfterAll {
if ($skipTest) { return }
if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue }
}
It "Pipeline binding works even when also binding by name" -Skip:$skipTest {
(Get-Date | foo) | Should Be "Bound parameter: date"
}
It "Pipeline binding works even when also binding by name" -Skip:$skipTest {
([ipaddress]::parse("127.0.0.1") | foo) | Should Be "Bound parameter: ipaddress"
}
It "Pipeline binding works even when also binding by name" -Skip:$skipTest {
([ipaddress]::parse("127.0.0.1") | foo -date $(Get-Date)) | Should Be "Bound parameter: date ipaddress"
}
It "Pipeline binding works even when also binding by name" -Skip:$skipTest {
(Get-Date | foo -ipaddress ([ipaddress]::parse("127.0.0.1"))) | Should Be "Bound parameter: date ipaddress"
}
}
Context "value from pipeline by property name - multiple parameters" {
BeforeAll {
if ($skipTest) { return }
Invoke-Command -Session $session -ScriptBlock {
function foo {
param(
[System.TimeSpan]