forked from PowerShell/Remotely
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Remotely.psm1
255 lines (200 loc) · 8.34 KB
/
Remotely.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
function Remotely {
<#
.SYNOPSIS
Executes a script block against a remote runspace. Remotely can be used with Pester for executing script blocks on remote system.
.DESCRIPTION
The contents on the Remotely block are executed on a remote runspace. The connection information of the runspace is supplied in a CSV file of the format:
ComputerName,Username,Password
machinename,user,password
The file name must be machineConfig.csv
The CSV file is expected to be placed next to this file.
If the CSV file is not found or username is not specified, the machine name is ignored and runspace to localhost
is created for executing the script block.
If the password has a ',' then it needs to be escaped by using quotes like:
ComputerName,Username,Password
machinename,user,"Some,password"
To get access to the streams GetVerbose, GetDebugOutput, GetError, GetProgressOutput, GetWarning can be used on the resultant object.
.PARAMETER Test
The script block that should throw an exception if the expectation of the test is not met.
.PARAMETER ArgumentList
Arguments that will be passed to the script block.
.EXAMPLE
Describe "Add-Numbers" {
It "adds positive numbers" {
Remotely { 2 + 3 } | Should Be 5
}
It "gets verbose message" {
$sum = Remotely { Write-Verbose -Verbose "Test Message" }
$sum.GetVerbose() | Should Be "Test Message"
}
It "can pass parameters to remote block" {
$num = 10
$process = Remotely { param($number) $number + 1 } -ArgumentList $num
$process | Should Be 11
}
}
.LINK
https://github.com/PowerShell/Remotely
https://github.com/pester/Pester
#>
param(
[Parameter(Mandatory = $true, Position = 0)]
[ScriptBlock] $test = {},
[Parameter(Mandatory = $false, Position = 1)]
$ArgumentList
)
if($script:sessionsHashTable -eq $null)
{
$script:sessionsHashTable = @{}
}
$machineConfigFile = Join-Path $PSScriptRoot "machineConfig.CSV"
CreateSessions -machineConfigFile $machineConfigFile
$sessions = @()
foreach($sessionInfo in $script:sessionsHashTable.Values.GetEnumerator())
{
CheckAndReConnect -sessionInfo $sessionInfo
$sessions += $sessionInfo.Session
}
if($sessions.Count -le 0)
{
throw "No sessions are available"
}
$testjob = Invoke-Command -Session $sessions -ScriptBlock $test -AsJob -ArgumentList $ArgumentList | Wait-Job
$results = @()
foreach($childJob in $testjob.ChildJobs)
{
if($childJob.Output.Count -eq 0)
{
[object] $outputStream = New-Object psobject
}
else
{
[object] $outputStream = $childJob.Output | % { $_ }
}
$errorStream = CopyStreams $childJob.Error
$verboseStream = CopyStreams $childJob.Verbose
$debugStream = CopyStreams $childJob.Debug
$warningStream = CopyStreams $childJob.Warning
$progressStream = CopyStreams $childJob.Progress
$allStreams = @{
Error = $errorStream
Verbose = $verboseStream
DebugOutput = $debugStream
Warning = $warningStream
ProgressOutput = $progressStream
}
$outputStream = Add-Member -InputObject $outputStream -PassThru -MemberType NoteProperty -Name __Streams -Value $allStreams
$outputStream = Add-Member -InputObject $outputStream -PassThru -MemberType ScriptMethod -Name GetError -Value { return $this.__Streams.Error }
$outputStream = Add-Member -InputObject $outputStream -PassThru -MemberType ScriptMethod -Name GetVerbose -Value { return $this.__Streams.Verbose }
$outputStream = Add-Member -InputObject $outputStream -PassThru -MemberType ScriptMethod -Name GetDebugOutput -Value { return $this.__Streams.DebugOutput }
$outputStream = Add-Member -InputObject $outputStream -PassThru -MemberType ScriptMethod -Name GetProgressOutput -Value { return $this.__Streams.ProgressOutput }
$outputStream = Add-Member -InputObject $outputStream -PassThru -MemberType ScriptMethod -Name GetWarning -Value { return $this.__Streams.Warning }
$outputStream = Add-Member -InputObject $outputStream -PassThru -MemberType NoteProperty -Name RemotelyTarget -Value $childJob.Location
if($childJob.State -eq 'Failed')
{
$childJob | Receive-Job -ErrorAction SilentlyContinue -ErrorVariable jobError
$outputStream.__Streams.Error = $jobError
}
$results += ,$outputStream
}
$testjob | Remove-Job -Force
$results
}
function CopyStreams
{
param( [Parameter(Position=0, Mandatory=$true)] $inputStream)
$outStream = New-Object 'System.Management.Automation.PSDataCollection[PSObject]'
foreach($item in $inputStream)
{
$outStream.Add($item)
}
$outStream.Complete()
,$outStream
}
function CreateSessions
{
param([string] $machineConfigFile)
if(Test-Path $machineConfigFile)
{
Write-Verbose "Found machine configuration file: $machineConfigFile"
$machineInfo = Import-Csv $machineConfigFile
foreach($item in $machineInfo)
{
if([String]::IsNullOrEmpty($item.UserName))
{
Write-Verbose "No username specified. Creating session to localhost."
CreateLocalSession $item.ComputerName
}
else
{
$password = ConvertTo-SecureString -String $item.Password -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $item.Username,$password
if(-not $script:sessionsHashTable.ContainsKey($item.ComputerName))
{
$sessionName = "Remotely" + (Get-Random).ToString()
$sessionInfo = CreateSessionInfo -Session (New-PSSession -ComputerName $item.ComputerName -Credential $cred -Name $sessionName) -Credential $cred
$script:sessionsHashTable.Add($sessionInfo.session.ComputerName, $sessionInfo)
}
}
}
}
else
{
Write-Verbose "No machine configuration file found. Creating session to localhost."
CreateLocalSession
}
}
function CreateLocalSession
{
param(
[Parameter(Position=0)] $machineName = 'localhost'
)
#if(-not $script:sessionsHashTable.ContainsKey("localhost"))
if(-not $script:sessionsHashTable.ContainsKey($machineName))
{
$sessionName = "Remotely" + (Get-Random).ToString()
$sessionInfo = CreateSessionInfo -Session (New-PSSession -ComputerName $machineName -Name $sessionName)
$script:sessionsHashTable.Add($machineName, $sessionInfo)
}
}
function CreateSessionInfo
{
param(
[Parameter(Position=0, Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.Management.Automation.Runspaces.PSSession] $Session,
[System.Management.Automation.PSCredential] $Credential
)
return [PSCustomObject] @{ Session = $Session; Credential = $Credential }
}
function CheckAndReconnect
{
param([Parameter(Position=0, Mandatory=$true)] [ValidateNotNullOrEmpty()] $sessionInfo)
if($sessionInfo.Session.State -ne [System.Management.Automation.Runspaces.RunspaceState]::Opened)
{
Write-Verbose "Unexpected session state: $sessionInfo.Session.State for machine $($sessionInfo.Session.ComputerName). Re-creating session"
if($sessionInfo.Session.ComputerName -ne "localhost")
{
$sessionInfo.Session = New-PSSession -ComputerName $sessionInfo.Session.ComputerName -Credential $sessionInfo.Credential
}
else
{
$sessionInfo.Session = New-PSSession -ComputerName 'localhost'
}
}
}
function Clear-RemoteSession
{
foreach($sessionInfo in $script:sessionsHashTable.Values.GetEnumerator())
{
Remove-PSSession $sessionInfo.Session
}
$script:sessionsHashTable.Clear()
}
function Get-RemoteSession
{
$sessions = @()
foreach($sessionInfo in $script:sessionsHashTable.Values.GetEnumerator())
{
$sessions += $sessionInfo.Session
}
$sessions
}