forked from exactmike/OneShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystemConnectionFunctions.ps1
More file actions
1211 lines (1208 loc) · 53.6 KB
/
SystemConnectionFunctions.ps1
File metadata and controls
1211 lines (1208 loc) · 53.6 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
##########################################################################################################
#Remote System Connection Functions
##########################################################################################################
function Find-EndPointToUse
{
[cmdletbinding()]
param
(
[parameter()]
[AllowNull()]
$EndPointIdentity
,
$ServiceObject
,
$EndPointGroup
,
[parameter()]
[ValidateSet('Admin', 'MRS')]
$EndPointType = 'Admin'
)
$FilteredEndpoints = @(
switch ($null -eq $EndPointIdentity)
{
$false
{
Write-verbose -Message "Endpoint Identity was specified. Return only that endpoint."
if ($EndPointIdentity -notin $ServiceObject.EndPoints.Identity)
{throw("Invalid EndPoint Identity $EndPointIdentity was specified. System $($ServiceObject.Identity) has no such endpoint.")}
else
{
$ServiceObject.EndPoints | Where-Object -FilterScript {$_.Identity -eq $EndPointIdentity}
}
}
$true
{
Write-verbose -message "Endpoint Identity was not specified. Return all applicable endpoints, with preferred first if specified."
switch ($null -eq $ServiceObject.PreferredEndpoint)
{
$false
{
Write-Verbose -Message "Preferred Endpoint is specified."
$PreEndpoints = @(
switch ($null -eq $EndPointGroup)
{
$true
{
Write-Verbose -message 'EndPointGroup was not specified'
$ServiceObject.EndPoints | Where-Object -FilterScript {$_.EndpointType -eq $EndpointType} | Sort-Object -Property Precedence
}#end false
$false
{
Write-Verbose -message 'EndPointGroup was specified'
$ServiceObject.EndPoints | Where-Object -FilterScript {$_.EndpointType -eq $EndpointType -and $_.EndPointGroup -eq $EndPointGroup} | Sort-Object -Property Precedence
}#end true
}#end switch
)
$PreEndpoints | Where-Object {$_.Identity -eq $ServiceObject.PreferredEndpoint} | ForEach-Object {$_.Precedence = -1}
$PreEndpoints
}#end false
$true
{
Write-Verbose -Message "Preferred Endpoint is not specified."
switch ($null -eq $EndPointGroup)
{
$true
{
Write-Verbose -message 'EndPointGroup was not specified'
$ServiceObject.EndPoints | Where-Object -FilterScript {$_.EndpointType -eq $EndpointType} | Sort-Object -Property Precedence
}#end false
#EndPointGroup was specified
$false
{
Write-Verbose -message 'EndPointGroup was specified'
$ServiceObject.EndPoints | Where-Object -FilterScript {$_.EndpointType -eq $EndpointType -and $_.EndPointGroup -eq $EndPointGroup} | Sort-Object -Property Precedence
}#end true
}#end switch
}#end true
}#end switch
}#end $true
}#end switch
)
$GroupedEndpoints = @($FilteredEndpoints | Group-Object -Property Precedence)
$GroupedEndpoints
}
#end function Find-EndPointToUse
function Get-WellKnownEndPoint
{
[cmdletbinding()]
param
(
$ServiceObject
)
$ServiceTypeDefinition = Get-OneShellServiceTypeDefinition -ServiceType $ServiceObject.ServiceType
@(
[PSCustomObject]@{
Identity = $ServiceObject.ServiceType + '-WellKnownEndPoint'
AddressType = 'URL'
Address = $ServiceTypeDefinition.WellKnownEndPointURI
ServicePort = $null
UseTLS = $false
ProxyEnabled = $ServiceObject.Defaults.ProxyEnabled
CommandPrefix = $ServiceObject.Defaults.CommandPrefix
AuthenticationRequired = $true
AuthMethod = $ServiceTypeDefinition.WellKnownEndPointAuthMethod
EndPointGroup = $null
EndPointType = 'Admin'
ServiceTypeAttributes = $null
ServiceType = $ServiceObject.ServiceType
Precedence = -1
PSRemoting = $true
}
) | Group-Object
}
#end function Find-ExchangeOnlineEndpointToUse
function Find-CommandPrefixToUse
{
[CmdletBinding()]
param
(
[parameter(Mandatory)]
$ServiceObject
)
$CommandPrefix = $(
if ($null -ne $ServiceObject.PreferredPrefix) #this allows a blank string to be the PreferredPrefix . . . which is what an user may want
{
$ServiceObject.PreferredPrefix
}
else
{
if ($null -ne $endpoint.CommandPrefix)
{
$endpoint.CommandPrefix
}
else
{
$ServiceObject.Defaults.CommandPrefix
}
}
)
$CommandPrefix
}
#end function Find-CommandPrefixToUse
function Get-OneShellSystem
{
[cmdletbinding(DefaultParameterSetName = 'Identity')]
param
(
)
DynamicParam
{
if ($null -eq $script:CurrentUserProfile)
{throw('No OneShell User Profile is active. Use function Use-OneShellUserProfile to load an User Profile.')}
$AvailableServiceTypes = @($script:CurrentSystems | Select-object -ExpandProperty ServiceType | Select-Object -Unique)
$AvailableOneShellSystemNamesAndIdentities = @($script:CurrentSystems.Name; $script:CurrentSystems.Identity)
$Dictionary = New-DynamicParameter -Name Identity -Type $([String[]]) -Mandatory $false -ValidateSet $AvailableOneShellSystemNamesAndIdentities -Position 1 -ParameterSetName Identity
$Dictionary = New-DynamicParameter -Name ServiceType -Type $([String[]]) -Mandatory $false -ValidateSet $AvailableServiceTypes -Position 1 -DPDictionary $Dictionary -ParameterSetName ServiceType
$Dictionary
}#DynamicParam
begin
{
Set-DynamicParameterVariable -dictionary $dictionary
}
Process
{
switch ($PSCmdlet.ParameterSetName)
{
'Identity'
{
if ($null -eq $Identity)
{
$script:CurrentSystems
}
foreach ($i in $Identity)
{
$script:CurrentSystems | Where-Object -FilterScript {$_.Identity -eq $i -or $_.name -eq $i}
}
}
'ServiceType'
{
$script:CurrentSystems | Where-Object -FilterScript {$_.ServiceType -in $ServiceType}
}
}
}
}
#end function Get-OneShellSystem
function GetOneShellSystemPSSession
{
[cmdletbinding()]
param
(
$ServiceObject
)
[string]$SessionNameWildcard = $($ServiceObject.Identity) + '*'
$message = "Run Get-PSSession for name like $SessionNameWildcard"
try
{
Write-OneShellLog -Message $message -EntryType Attempting
$ServiceSession = @(Get-PSSession -Name $SessionNameWildcard -ErrorAction Stop)
Write-OneShellLog -Message $message -EntryType Succeeded
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
}
$ServiceSession
}
#end function GetOneShellSystemPSSession
function Get-OneShellSystemPSSession
{
[cmdletbinding(DefaultParameterSetName = 'ServiceObject')]
param
(
[parameter(Mandatory, ParameterSetName = 'ServiceObject')]
$serviceObject
)
DynamicParam
{
if ($null -eq $script:CurrentUserProfile)
{throw('No OneShell User Profile is active. Use function Use-OneShellUserProfile to load an User Profile.')}
$AvailableOneShellSystemNamesAndIdentities = @($script:CurrentSystems.Name; $script:CurrentSystems.Identity)
$Dictionary = New-DynamicParameter -Name Identity -Type $([String[]]) -Mandatory $true -ValidateSet $AvailableOneShellSystemNamesAndIdentities -Position 1 -ParameterSetName Identity -ValueFromPipelineByPropertyName $true -ValueFromPipeline $true
$Dictionary
}#DynamicParam
begin
{
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
}
process
{
switch ($PSCmdlet.ParameterSetName)
{
'Identity'
{
Set-DynamicParameterVariable -dictionary $Dictionary
foreach ($i in $Identity)
{
$ServiceObject = $script:CurrentSystems | Where-Object -FilterScript {$_.Identity -eq $i -or $_.name -eq $i}
GetOneShellSystemPSSession -ServiceObject $ServiceObject
}
}
'ServiceObject'
{
GetOneShellSystemPSSession -ServiceObject $ServiceObject
}
}
}
}
#end function Get-OneShellSystemPSSession
function Test-OneShellSystemConnection
{
[cmdletbinding()]
param
(
$serviceObject
,
[switch]$ReturnSession
)
begin
{
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
}
end
{
try
{
$ServiceSession = @(Get-OneShellSystemPSSession -serviceObject $serviceObject -ErrorAction Stop)
}
catch
{
Write-OneShellLog -Message $_.tostring() -ErrorLog
}
switch ($ServiceSession.Count)
{
1
{
$ServiceSession = $ServiceSession[0]
$message = "Found PSSession $($ServiceSession.name) for service $($serviceObject.Name)."
Write-OneShellLog -Message $message -EntryType Notification
#Test the Session functionality
if ($ServiceSession.state -ne 'Opened')
{
Write-OneShellLog -Message "PSSession $($ServiceSession.name) for service $($serviceObject.Name) is not in state 'Opened'." -EntryType Notification
$false
break
}
else
{
Write-OneShellLog -Message "PSSession $($ServiceSession.name) for service $($serviceObject.Name) is in state 'Opened'." -EntryType Notification
}
Write-OneShellLog -Message "Getting Service Type Session Test Commands" -EntryType Notification
$ServiceTypeDefinition = Get-OneShellServiceTypeDefinition -ServiceType $ServiceObject.ServiceType -ErrorAction Stop
if ($null -ne $ServiceTypeDefinition.SessionTestCmdlet)
{
$testCommand = $ServiceTypeDefinition.SessionTestCmdlet
$TestCommandParams = @{
ErrorAction = 'Stop'
}
#$testCommandParams.WarningAction = 'SilentlyContinue' #don't add because in constrained PSSessions this might not be allowed
if ($null -ne $ServiceTypeDefinition.SessionTestCmdletParameters -and $ServiceTypeDefinition.SessionTestCmdletParameters.count -ge 1)
{
foreach ($p in $ServiceTypeDefinition.SessionTestCmdletParameters)
{
$value = $(
switch ($p.ValueType)
{
'Static'
{$p.Value}
'ScriptBlock'
{
$ValueGeneratingScriptBlock = [scriptblock]::Create($p.Value)
&$ValueGeneratingScriptBlock
}
}
)
$TestCommandParams.$($p.name) = $value
}
}
Write-OneShellLog -Message "Found Service Type Command to use for $($serviceObject.ServiceType): $testCommand" -EntryType Notification
$message = "Run $testCommand in $($serviceSession.name) PSSession"
try
{
Write-OneShellLog -Message $message -EntryType Attempting
[void](invoke-command -Session $ServiceSession -ScriptBlock {&$Using:TestCommand @using:TestCommandParams} -ErrorAction Stop)
Write-OneShellLog -Message $message -EntryType Succeeded
$true
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed -ErrorLog
Write-OneShellLog -message $myerror.tostring() -ErrorLog
$false
break
}
}#end if
else
{
Write-OneShellLog "No Service Type Command to use for Service Testing is specified for ServiceType $($ServiceObject.ServiceType)."
$true
}
}
0
{
$message = "Found No PSSession for service $($serviceObject.Name)."
Write-OneShellLog -Message $message -EntryType Notification
$false
}
Default
{
$message = "Found multiple PSSessions $($ServiceSession.name -join ',') for service $($serviceObject.Name). Please delete one or more sessions then try again."
Write-OneShellLog -Message $message -EntryType Failed -ErrorLog
$false
}
}
if ($ReturnSession)
{$ServiceSession}
}
}
#end function Test-OneShellSystemConnection
function Get-OneShellSystemEndpointPSSessionParameter
{
[cmdletbinding()]
param
(
$ServiceObject
,
$Endpoint
)
begin
{
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
}#end begin
end
{
$ServiceTypeDefinition = Get-OneShellServiceTypeDefinition -ServiceType $ServiceObject.ServiceType
$NewPSSessionParams = @{
ErrorAction = 'Stop'
Name = $($ServiceObject.Identity + '%' + $Endpoint.Identity)
}
if ($null -ne $ServiceObject.Credentials.PSSession)
{
$NewPSSessionParams.Credential = $ServiceObject.Credentials.PSSession
}
#Apply Service Type Defaults
foreach ($p in $ServiceTypeDefinition.PSSessionParameters)
{
$value = $(
switch ($p.ValueType)
{
'Static'
{$p.Value}
'ScriptBlock'
{
& $([scriptblock]::Create($p.Value))
}
}
)
$NewPSSessionParams.$($p.name) = $value
}
#Apply ServiceObject Defaults or their endpoint overrides
if ($ServiceObject.defaults.ProxyEnabled -eq $true -or $Endpoint.ProxyEnabled -eq $true)
{
$NewPSSessionParams.SessionOption = New-PsSessionOption -ProxyAccessType IEConfig #-ProxyAuthentication basic
}
if ($ServiceObject.defaults.UseTLS -eq $true -or $Endpoint.UseTLS -eq $true)
{
$NewPSSessionParams.UseSSL = $true
}
if (Test-IsNotNullOrWhiteSpace -string $ServiceObject.defaults.AuthMethod)
{
$NewPSSessionParams.Authentication = $ServiceObject.defaults.AuthMethod
}
if (Test-IsNotNullOrWhiteSpace -String $endpoint.AuthMethod)
{
$NewPSSessionParams.Authentication = $Endpoint.AuthMethod
}
#Apply Endpoint only settings
if (Test-IsNotNullOrWhiteSpace -String $endpoint.ServicePort)
{
$NewPSSessionParams.Port = $Endpoint.ServicePort
}
$NewPSSessionParams
}#end end
}
#end function Get-EndPointPSSessionParameter
Function Connect-OneShellSystem
{
[cmdletbinding(DefaultParameterSetName = 'Default')]
Param
(
[parameter(ParameterSetName = 'EndPointIdentity')]
[ValidateNotNullOrEmpty()]
[string]$EndPointIdentity #An endpoint identity from existing endpoints configure for this system. Overrides the otherwise specified endpoint.
,
[parameter(ParameterSetName = 'EndPointGroup')]
[ValidateNotNullOrEmpty()]
[string]$EndPointGroup #An endpoint identity from existing endpoints configure for this system. Overrides the otherwise specified endpoint.
,
[parameter()]
[ValidateScript( {($_.length -ge 2 -and $_.length -le 5) -or [string]::isnullorempty($_)})]
[string]$CommandPrefix #Overrides the otherwise specified command prefix.
,
[parameter()]
[ValidateSet('PowerShell', 'SQLDatabase', 'ExchangeOnPremises', 'ExchangeOnline', 'ExchangeComplianceCenter', 'AADSyncServer', 'AzureAD', 'AzureADPreview', 'MSOnline', 'ActiveDirectoryDomain', 'ActiveDirectoryGlobalCatalog', 'ActiveDirectoryLDS', 'SMTPMailRelay', 'SkypeForBusinessOnline', 'SkypeForBusinessOnPremises')]
[string[]]$ServiceType #used only to filter list of available system identities and names
,
[parameter()]
[switch]$NoAutoImport
,
[parameter(Mandatory, ParameterSetName = 'Reconnect')]
[switch]$Reconnect
)
DynamicParam
{
if ($null -ne $serviceType)
{
$AvailableOneShellSystems = @(Get-OneShellSystem -ServiceType $ServiceType)
}
else
{
$AvailableOneShellSystems = @(Get-OneShellSystem)
}
$AvailableOneShellSystemNamesAndIdentities = @($AvailableOneShellSystems.Name; $AvailableOneShellSystems.Identity)
$Dictionary = New-DynamicParameter -Name Identity -Type $([String[]]) -Mandatory $false -ValidateSet $AvailableOneShellSystemNamesAndIdentities -Position 1 -ValueFromPipelineByPropertyName $true -ValueFromPipeline $true
$Dictionary
}#DynamicParam
begin
{
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
}
process
{
Set-DynamicParameterVariable -dictionary $Dictionary
if ($PSCmdlet.ParameterSetName -eq 'Reconnect')
{
$Identity = @(Get-Pssession | Where-Object {$_.State -eq 'Broken'} | ForEach-Object {$_.name.split('%')[0]} | Where-Object {$_ -in $AvailableOneShellSystemNamesAndIdentities})
}
foreach ($id in $Identity)
{
$ServiceObject = $AvailableOneShellSystems | Where-Object -FilterScript {$_.name -eq $id -or $_.Identity -eq $id}
Write-Verbose -Message "Using Service/System: $($serviceObject.Name)"
$ServiceTypeDefinition = Get-OneShellServiceTypeDefinition -ServiceType $ServiceObject.ServiceType -errorAction Stop
Write-Verbose -Message "Using ServiceTypeDefinition: $($serviceTypeDefinition.Name)"
$EndPointGroups = @(
Write-Verbose -Message "Selecting an Endpoint"
switch ($ServiceTypeDefinition.DefaultsToWellKnownEndPoint -and ($null -eq $EndPointIdentity -or (Test-IsNullOrWhiteSpace -String $EndPointIdentity)))
{
$true
{
Write-Verbose -Message "Get Well Known Endpoint(s)."
Get-WellKnownEndPoint -ServiceObject $ServiceObject -ErrorAction Stop
}
Default
{
$FindEndPointToUseParams = @{
ErrorAction = 'Stop'
ServiceObject = $ServiceObject
}
switch ($PSCmdlet.ParameterSetName)
{
'Default'
{}
'EndPointIdentity'
{$FindEndPointToUseParams.EndPointIdentity = $EndPointIdentity}
'EndPointGroup'
{$FindEndPointToUseParams.EndPointGroup = $EndPointGroup}
Default
{}
}
Find-EndPointToUse @FindEndPointToUseParams
}
}
)
if ($null -eq $EndPointGroups -or $EndPointGroups.Count -eq 0)
{throw("No endpoint found for system $($serviceObject.Name), $($serviceObject.Identity)")}
#Test for an existing connection
switch ($ServiceObject.defaults.UsePSRemoting -or $true)
{
$true
{
$ExistingConnectionIsValid, $ExistingSession = Test-OneShellSystemConnection -serviceObject $ServiceObject -ErrorAction Stop -ReturnSession
#check results of the test for an existing session
if ($ExistingConnectionIsValid)
{
Write-OneShellLog -Message "Existing Session $($ExistingSession.name) for Service $($serviceObject.Name) is valid."
#nothing further to do since existing connection is valid
#add logic for preferred endpoint/specified endpoint checking?
}#end if
else
{
if ($null -ne $ExistingSession)
{
try
{
if ($script:ImportedSessionModules.ContainsKey($ServiceObject.Identity))
{
$ImportedSessionModule = $script:ImportedSessionModules.$($ServiceObject.Identity)
$message = "Remove Previously Imported Session Module $ImportedSessionModule for System $($ServiceObject.Identity)"
try
{
Write-OneShellLog -Message $message -EntryType Attempting
Remove-Module -Name $ImportedSessionModule.Name -ErrorAction Stop
Write-OneShellLog -Message $message -EntryType Succeeded
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed -ErrorLog
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
}
}
$message = "Remove Existing Invalid Session $($ExistingSession.name) for Service $($serviceObject.name)."
Try
{
Write-OneShellLog -Message $message -EntryType Attempting
Remove-PSSession -Session $ExistingSession -ErrorAction Stop
Write-OneShellLog -Message $message -EntryType Succeeded
}
Catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed -ErrorLog
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
}
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed -ErrorLog
Write-OneShellLog -Message $myerror.tostring() -EntryType -ErrorLog
throw ($myerror)
}
}#end if
Write-OneShellLog -Message "No Existing Valid Session found for $($ServiceObject.name)" -EntryType Notification
#create and test the new session
$ConnectionReady = $false #we switch this to true when a session is connected and initialized with required modules and settings
#Work through the endpoint groups to try connecting in order of precedence
for ($i = 0; $i -lt $EndPointGroups.count -and $ConnectionReady -eq $false; $i++)
{
#get the first endpoint group and randomly order them, then work through them one at a time until successfully connected
$g = $endPointGroups[$i]
$endpoints = @($g.group | Sort-Object -Property {Get-Random})
for ($ii = 0; $ii -lt $endpoints.Count -and $ConnectionReady -eq $false; $ii++)
{
$e = $endpoints[$ii]
$NewPSSessionParams = Get-OneShellSystemEndpointPSSessionParameter -ServiceObject $ServiceObject -Endpoint $e -ErrorAction Stop
$NewPSSessionCmdlet = 'New-PSSession'
try
{
if ($null -ne $ServiceTypeDefinition.PSSessionCmdlet)
{
$NewPSSessionCmdlet = $ServiceTypeDefinition.PSSessionCmdlet
}
$message = "Create PsSession using command $NewPSsessionCmdlet with name $($NewPSSessionParams.Name) for Service $($serviceObject.Name)"
Write-OneShellLog -Message $message -EntryType Attempting
$ServiceSession = Invoke-Command -ScriptBlock {& $NewPSSessionCmdlet @NewPSSessionParams}
Write-OneShellLog -Message $message -EntryType Succeeded
$PSSessionConnected = $true
}#end Try
catch
{
$myerror = $_
$PSSessionConnected = $false
Write-OneShellLog -Message $message -EntryType Failed -ErrorLog
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
}#end Catch
#determine if the session needs to be initialized with imported modules, variables, etc. based on ServiceType
$Phase1InitializationCompleted = $(
if ($PSSessionConnected -eq $true)
{
$message = "Perform Phase 1 Initilization of PSSession $($serviceSession.Name) for $($serviceObject.Name)"
try
{
Write-OneShellLog -Message $message -EntryType Attempting
Initialize-OneShellSystemPSSession -Phase Phase1_PreModuleImport -ServiceObject $ServiceObject -ServiceSession $ServiceSession -endpoint $e -ErrorAction Stop
Write-OneShellLog -Message $message -EntryType Succeeded
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
$false
}
}
else
{
$false
}
)
$Phase2InitializationCompleted = $(
if ($Phase1InitializationCompleted -ne $false)
{
try
{
$message = "Import Required Module(s) into PSSession $($serviceSession.Name) for $($serviceObject.Name)"
Write-OneShellLog -Message $message -EntryType Attempting
Import-ModuleInOneShellSystemPSSession -ServiceObject $ServiceObject -ServiceSession $ServiceSession -ErrorAction Stop
Write-OneShellLog -Message $message -EntryType Succeeded
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
$false
}
}
else
{
$false
}
)
$Phase3InitializationCompleted = $(
if ($Phase2InitializationCompleted -ne $false)
{
try
{
$message = "Perform Phase 3 Initilization of PSSession $($serviceSession.Name) for $($serviceObject.Name)"
Write-OneShellLog -Message $message -EntryType Attempting
Initialize-OneShellSystemPSSession -Phase Phase3 -ServiceObject $ServiceObject -ServiceSession $ServiceSession -endpoint $e -ErrorAction Stop
Write-OneShellLog -Message $message -EntryType Succeeded
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -EntryType Failed
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
$false
}
#determine if the session needs further initialization
}#end if
else
{
$false
}
)
$message = "Connection and Initialization of PSSession $($serviceSession.name) for $($serviceobject.name)"
if (@($Phase1InitializationCompleted, $Phase2InitializationCompleted, $Phase3InitializationCompleted) -notcontains $false)
{
Write-OneShellLog -Message $message -EntryType Succeeded
$ConnectionReady = $true
}
else
{
Write-OneShellLog -Message $message -EntryType Failed -ErrorLog
if ($null -ne $ServiceSession)
{
Remove-PSSession -Session $ServiceSession -ErrorAction Stop
}
}
}#end for
}#end for
switch ($ConnectionReady)
{
$false #we couldn't connect after trying all applicable endpoints
{
Write-OneShellLog -Message "Failed to Connect to $($ServiceObject.Name). Review the errors and resolve them to connect." -ErrorLog -Verbose
}
$true
{
Write-OneShellLog -Message "Successfully Connected to $($ServiceObject.Name) with PSSession $($ServiceSession.Name)" -Verbose
$SessionManagementGroups = @(
if ($null -ne $ServiceObject.ServiceTypeAttributes -and $null -ne $ServiceObject.ServiceTypeAttributes.SessionManagementGroups)
{
$ServiceObject.ServiceTypeAttributes.SessionManagementGroups
}
$ServiceObject.ServiceType
)
Update-SessionManagementGroup -ServiceSession $ServiceSession -ManagementGroups $SessionManagementGroups
if ($ServiceObject.AutoImport -eq $true -and $NoAutoImport -ne $true)
{
Import-OneShellSystemPSSession -ServiceObject $ServiceObject -ServiceSession $ServiceSession
}
}
}
}
}#end $true
default
{
Write-Warning -Message "This version of OneShell does not yet test for existing connections to services/systems configured with UsePSRemoting: False"
}#end $false
}#end Switch
}#end foreach i in Identity
}#end Process
}
#end function Connect-OneShellSystem
function Import-ModuleInOneShellSystemPSSession
{
[CmdletBinding()]
param
(
[parameter(Mandatory)]
$ServiceObject
,
[parameter(Mandatory)]
$ServiceSession
)
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
$ServiceTypeDefinition = Get-OneShellServiceTypeDefinition -ServiceType $ServiceObject.ServiceType
$ModuleImportResults = @(
if ($null -ne $ServiceTypeDefinition.PSSessionSettings.Initialization.Phase2_ModuleImport -and $ServiceTypeDefinition.PSSessionSettings.Initialization.Phase2_ModuleImport.count -ge 1)
{
foreach ($m in $ServiceTypeDefinition.PSSessionSettings.Initialization.Phase2_ModuleImport)
{
$ModuleName = $m.name
$ImportModuleParams = @{
Name = $ModuleName
ErrorAction = 'Stop'
}
switch ($m.type)
{
'PSSnapIn'
{
$ImportCommand = 'Add-PSSnapin'
}
default
{
$ImportCommand = 'Import-Module'
}
}
try
{
$message = "import required module $ModuleName into PSSession $($ServiceSession.name) for System $($serviceObject.Name)."
Write-OneShellLog -Message $message -EntryType Attempting
Invoke-Command -session $ServiceSession -ScriptBlock {&$using:ImportCommand @using:ImportModuleParams} -ErrorAction Stop
Write-OneShellLog -Message $message -EntryType Succeeded
$ModuleImported = $true
}
catch
{
$myerror = $_
Write-OneShellLog -Message $message -ErrorLog -Verbose -EntryType Failed
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
$ModuleImported = $false
}
$ModuleImported
}
}#end if
)
switch ($ModuleImportResults)
{
{$_.count -eq 0}
{$null}
{$_ -contains $false}
{$false}
{$_ -notcontains $false -and $_ -contains $true}
{$true}
}
}
#end function Import-RequiredModuleIntoOneShellSystemPSSession
function Initialize-OneShellSystemPSSession
{
[CmdletBinding()]
param
(
[parameter(Mandatory)]
$ServiceObject
,
[parameter(Mandatory)]
$ServiceSession
,
[parameter(Mandatory)]
$endpoint
,
[parameter(Mandatory)]
[ValidateSet('Phase1_PreModuleImport', 'Phase3')]
$Phase
)
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
$ServiceTypeDefinition = Get-OneShellServiceTypeDefinition -ServiceType $ServiceObject.ServiceType
switch ($null -ne $ServiceTypeDefinition.PSSessionSettings.Initialization.$Phase -and ($ServiceTypeDefinition.PSSessionSettings.Initialization.$Phase).count -ge 1)
{
$true
{
$InitializationCommandsResults = @(
foreach ($cmd in $ServiceTypeDefinition.PSSessionSettings.Initialization.$phase)
{
$conditionResults = @(
foreach ($c in $cmd.conditions)
{
switch ($c.type)
{
'Local'
{
$ScriptBlockToTest = [scriptblock]::Create($c.test)
&$ScriptBlockToTest
}
'InPSSession'
{
Invoke-Command -Session $serviceSession -ScriptBlock {& $($($using:c).test)}
}
}
}
)
switch ($conditionResults -notcontains $false)
{
$true
{
$CmdParams = @{
ErrorAction = 'Stop'
}
foreach ($p in $cmd.parameters)
{
$value = $(
switch ($p.ValueType)
{
'Static'
{$p.Value}
'ScriptBlock'
{
$ValueGeneratingScriptBlock = [scriptblock]::Create($p.Value)
&$ValueGeneratingScriptBlock
}
}
)
if ($null -ne $value)
{
$CmdParams.$($p.name) = $value
}
}
Try
{
[void](Invoke-Command -Session $serviceSession -ScriptBlock {& $(($Using:cmd).command) @using:CmdParams} -ErrorAction Stop)
$true
}#end Try
Catch
{
$myerror = $_
Write-OneShellLog -Message "Initialization Phase $Phase failed." -ErrorLog -Verbose -EntryType Failed
Write-OneShellLog -Message $myerror.tostring() -ErrorLog
$false
}
}
$false
{
$null
}
}
}
)
#output True or false depending on results above
$InitializationCommandsResults -notcontains $false
}
$false
{
$null
}
}#end Switch
}
#end function Initialize-OneShellSystemPSSession
function Add-FunctionToPSSession
{
[cmdletbinding()]
param(
[parameter(Mandatory)]
[string[]]$FunctionNames
,
[parameter(ParameterSetName = 'SessionID', Mandatory, ValuefromPipelineByPropertyName)]
[int]$ID
,
[parameter(ParameterSetName = 'SessionName', Mandatory, ValueFromPipelineByPropertyName)]
[string]$Name
,
[parameter(ParameterSetName = 'SessionObject', Mandatory, ValueFromPipeline)]
[Management.Automation.Runspaces.PSSession]$PSSession
,
[switch]$Refresh
)
#Find the session
$GetPSSessionParams = @{
ErrorAction = 'Stop'
}
switch ($PSCmdlet.ParameterSetName)
{
'SessionID'
{
$GetPSSessionParams.ID = $ID
$PSSession = Get-PSSession @GetPSSessionParams
}
'SessionName'
{
$GetPSSessionParams.Name = $Name
$PSSession = Get-PSSession @GetPSSessionParams
}
'SessionObject'
{
#nothing required here
}
}
#Verify the session availability
if (-not $PSSession.Availability -eq 'Available')
{
throw "Availability Status for PSSession $($PSSession.Name) is $($PSSession.Availability). It must be Available."
}
#Verify if the functions already exist in the PSSession unless Refresh
foreach ($FN in $FunctionNames)
{
$script = "Get-Command -Name '$FN' -ErrorAction SilentlyContinue"
$scriptblock = [scriptblock]::Create($script)
$remoteFunction = Invoke-Command -Session $PSSession -ScriptBlock $scriptblock -ErrorAction SilentlyContinue
if ($null -ne $remoteFunction.CommandType -and -not $Refresh)
{
$FunctionNames = $FunctionNames | Where-Object -FilterScript {$_ -ne $FN}
}
}
Write-Verbose -Message "Functions remaining: $($FunctionNames -join ',')"
#Verify the local function availiability
$Functions = @(
foreach ($FN in $FunctionNames)
{
Get-Command -ErrorAction Stop -Name $FN -CommandType Function
}
)
#build functions text to initialize in PsSession
$FunctionsText = ''
foreach ($Function in $Functions)
{
$FunctionText = 'function ' + $Function.Name + "`r`n {`r`n" + $Function.Definition + "`r`n}`r`n"
$FunctionsText = $FunctionsText + $FunctionText
}
#convert functions text to scriptblock
$ScriptBlock = [scriptblock]::Create($FunctionsText)
Invoke-Command -Session $PSSession -ScriptBlock $ScriptBlock -ErrorAction Stop
}
#end function Add-FunctionToPSSession
Function Update-SessionManagementGroup
{
[cmdletbinding()]
Param
(
[parameter(Mandatory = $true)]
$ServiceSession
, [parameter(Mandatory = $true)]
[string[]]$ManagementGroups
)
foreach ($MG in $ManagementGroups)
{
$SessionGroup = $MG + '_PSSessions'
#Check if the Session Group already exists
if (Test-Path -Path "variable:\$SessionGroup")
{
#since the session group already exists, add the session to it if it is not already present
$ExistingSessions = Get-Variable -Name $SessionGroup -Scope Global -ValueOnly
$ExistingSessionNames = $existingSessions | Select-Object -ExpandProperty Name
if ($ServiceSession.name -in $ExistingSessionNames)
{
$NewValue = @($ExistingSessions | Where-Object -FilterScript {$_.Name -ne $ServiceSession.Name})
$NewValue += $ServiceSession
Set-Variable -Name $SessionGroup -Value $NewValue -Scope Global
}
else
{
$NewValue = $ExistingSessions + $ServiceSession
Set-Variable -Name $SessionGroup -Value $NewValue -Scope Global
}
}