forked from proxb/PoshRSJob
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Start-RSJob.ps1
247 lines (223 loc) · 10.8 KB
/
Start-RSJob.ps1
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
Function Start-RSJob {
<#
.SYNOPSIS
Starts a background job using runspaces.
.DESCRIPTION
This will run a command in the background, leaving your console available to perform other tasks. This uses
runspaces in runspacepools which allows for throttling of running jobs. As the jobs are finished, they will automatically
dispose of each runspace and allow other runspace jobs in queue to begin based on the throttling of the runspacepool.
This is available on PowerShell V3 and above. By doing this, you can use the $Using: variable to take variables
in the local scope and apply those directly into the scriptblock of the background runspace job.
.PARAMETER ScriptBlock
The scriptblock that holds all of the commands which will be run in the background runspace. You must specify
at least one Parameter in the Param() to account for the item that is being piped into Start-Job.
.PARAMETER FilePath
This is the path to a file containing code that will be run in the background runspace job.
.PARAMETER InputObject
The object being piped into Start-RSJob or applied via the parameter.
.PARAMETER Name
The name of a background runspace job
.PARAMETER ArgumentList
List of values that will be applied at the end of the argument list in the Param() statement.
.PARAMETER Throttle
Number of concurrent running runspace jobs which are allowed at a time.
.PARAMETER ModulesToImport
A collection of modules that will be imported into the background runspace job.
.PARAMETER FunctionsToImport
A collection of functions that will be imported for use with a background runspace job.
.NOTES
Name: Start-RSJob
Author: Boe Prox
.EXAMPLE
Get-ChildItem -Directory | Start-RSjob -Name {$_.Name} -ScriptBlock {
Param($Directory)
Write-Verbose $_
$Sum = (Get-ChildItem $Directory.FullName -Recurse -Force -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum).Sum
[pscustomobject]@{
Name = $Directory.Name
SizeMB = ([math]::round(($Sum/1MB),2))
}
}
Id Name State HasMoreData HasErrors Command
-- ---- ----- ----------- --------- -------
11 .shsh Running False False ...
12 .ssh Running False False ...
13 Contacts Running False False ...
14 Desktop Running False False ...
15 Documents Running False False ...
16 Downloads Running False False ...
17 Favorites Running False False ...
18 Links Running False False ...
19 Music Running False False ...
20 OneDrive Running False False ...
21 Pictures Running False False ...
22 Saved Games Running False False ...
23 Searches Running False False ...
24 Videos Running False False ...
Get-RSJob | Receive-RSJob
Name SizeMB
---- ------
.shsh 0
.ssh 0
Contacts 0
Desktop 7.24
Documents 83.99
Downloads 10259.6
Favorites 0
Links 0
Music 16691.89
OneDrive 1485.24
Pictures 1734.91
Saved Games 0
Searches 0
Videos 17.19
Description
-----------
Starts a background runspace job that looks at the total size of each folder. Using Get-RSJob | Recieve-RSJob shows
the results when the State is Completed.
.EXAMPLE
$Test = 'test'
$Something = 1..10
1..5|start-rsjob -Name {$_} -ScriptBlock {
Param($Object) [pscustomobject]@{
Result=($Object*2)
Test=$Using:Test
Something=$Using:Something
}
}
Id Name State HasMoreData HasErrors Command
-- ---- ----- ----------- --------- -------
76 1 Completed True False ...
77 2 Running False False ...
78 3 Running False False ...
79 4 Completed False False ...
80 5 Completed False False ...
Get-RSjob | Receive-RSJob
Result Test Something
------ ---- ---------
2 test {1, 2, 3, 4...}
4 test {1, 2, 3, 4...}
6 test {1, 2, 3, 4...}
8 test {1, 2, 3, 4...}
10 test {1, 2, 3, 4...}
Description
-----------
Shows an example of the $Using: variable being used in the scriptblock.
#>
[OutputType('PoshRS.PowerShell.RSJob')]
[cmdletbinding(
DefaultParameterSetName = 'All'
)]
Param (
[parameter(Position=0,ParameterSetName = 'ScriptBlock')]
[ScriptBlock]$ScriptBlock,
[parameter(Position=0,ParameterSetName = 'ScriptPath')]
[string]$FilePath,
[parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
[object]$InputObject,
[parameter()]
[object]$Name,
[parameter()]
[object]$ArgumentList,
[parameter()]
[int]$Throttle = 5,
[parameter()]
[string[]]$ModulesToImport,
[parameter()]
[string[]]$FunctionsToLoad
)
Begin {
If ($PSBoundParameters['Debug']) {
$DebugPreference = 'Continue'
}
If ($PSBoundParameters['Name']) {
If ($Name -isnot [scriptblock]) {
$Name = [scriptblock]::Create("Write-Output $Name")
} Else {
$Name = [scriptblock]::Create( ($Name -replace '\$_','$Object'))
}
} Else {
$Name = [scriptblock]::Create('Write-Output Job$($Id)')
}
$RunspacePoolID = [guid]::NewGuid().ToString()
Write-Verbose "Creating runspacepool <$($RunspacePoolID)> with max threads: $Throttle"
$InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
If ($PSBoundParameters['ModulesToImport']) {
[void]$InitialSessionState.ImportPSModule($ModulesToImport)
}
If ($PSBoundParameters['FunctionsToLoad']) {
ForEach ($Function in $FunctionsToLoad) {
Try {
$Definition = Get-Content Function:\$Function -ErrorAction Stop
$SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList $Function, $Definition
$InitialSessionState.Commands.Add($SessionStateFunction)
} Catch {
Write-Warning "$($Function): $($_.Exception.Message)"
}
}
}
$RunspacePool = [runspacefactory]::CreateRunspacePool(1,$Throttle,$InitialSessionState,$Host)
$RunspacePool.CleanupInterval = [timespan]::FromMinutes(2)
$RunspacePool.Open()
If ($PSBoundParameters['FilePath']) {
$ScriptBlock = [scriptblock]::Create((Get-Content $FilePath))
}
$RSPObject = [PoshRS.PowerShell.RSRunspacePool]@{
RunspacePool = $RunspacePool
MaxJobs = $RunspacePool.GetMaxRunspaces()
RunspacePoolID = $RunspacePoolID
}
#Convert ScriptBlock for $Using:
$UsingVariables = GetUsingVariables $ScriptBlock
If ($UsingVariables) {
Write-Verbose "Found $($UsingVariables.Count) '`$Using:' variables"
$UsingVariableValues = @(GetUsingVariableValues $UsingVariables)
$NewScriptBlock = ConvertScript $ScriptBlock
} Else {
$NewScriptBlock = $ScriptBlock
}
Write-Debug "ScriptBlock: $($NewScriptBlock)"
[System.Threading.Monitor]::Enter($RunspacePools.syncroot)
[void]$RunspacePools.Add($RSPObject)
[System.Threading.Monitor]::Exit($RunspacePools.syncroot)
}
Process {
ForEach ($Object in $InputObject) {
$RunspacePoolJobs++
$ID = Increment
Write-Verbose "Using $($Object) as pipline variable"
$PowerShell = [powershell]::Create().AddScript($NewScriptBlock)
$PowerShell.RunspacePool = $RunspacePool
[void]$PowerShell.AddArgument($Object)
If ($UsingVariableValues) {
For ($i=0;$i -lt $UsingVariableValues.count;$i++) {
Write-Verbose "Adding Param: $($UsingVariableValues[$i].Name) Value: $($UsingVariableValues[$i].Value)"
[void]$PowerShell.AddParameter($UsingVariableValues[$i].NewVarName,$UsingVariableValues[$i].Value)
}
}
ForEach ($item in $ArgumentList) {
Write-Verbose "Adding Argument: $($Item)"
[void]$PowerShell.AddArgument($item)
}
$Handle = $PowerShell.BeginInvoke()
$Object = [PoshRS.PowerShell.RSJob]@{
Name = $Name.InvokeReturnAsIs()
InstanceID = [guid]::NewGuid().ToString()
ID = $ID
Handle = $Handle
InnerJob = $PowerShell
Runspace = $PowerShell.Runspace
Finished = $handle.RSWaitHandle
Command = $ScriptBlock.ToString()
RunspacePoolID = $RunSpacePoolID
}
[System.Threading.Monitor]::Enter($Jobs.syncroot)
[void]$Jobs.Add($Object)
[System.Threading.Monitor]::Exit($Jobs.syncroot)
$Object
}
}
End {
}
}