Recently I’ve been writing a lot of script cmdlets in modules. One such cmdlet is used to wrap an executable which has the tendency to take a very long time to complete and I needed to run it more than ten times back to back. To attempt to speed things up I thought it would be great to add an –AsJob parameter to my script cmdlet. This way the cmdlet returns me a Powershell background job so that I can spin up multiple instances of my script cmdlet at the same time. Below is an example of my approach to implementing the –AsJob parameter to a simple script cmdlet.
Enjoy!
1 function Test-Job {
2 [CmdletBinding()]
3 param (
4 [parameter(mandatory=$true)] [String]
5 $Computer,
6
7 [parameter()] [Int16]
8 $Retries = 4,
9
10 [parameter()] [Switch]
11 $AsJob
12 )
13
14 $ScriptBlock = {
15 [CmdletBinding()]
16 param (
17 [parameter(mandatory=$true)] [String]
18 $Computer,
19
20 [parameter()] [Int16]
21 $Retries = 4
22 )
23
24 $output = & ping.exe $Computer -n $Retries 2>&1
25
26 if ($LASTEXITCODE -ne 0) {
27 throw $output
28 } else {
29 $output
30 }
31 }
32
33 if ($AsJob) {
34 Start-Job -ScriptBlock $ScriptBlock -ArgumentList `
35 $Computer, $Retries
36 } else {
37 Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList `
38 $Computer, $Retries
39 }
40 }
41
42 # Fails.
43 $job = Test-Job -Computer 127.0.0.0 -Retries 6 -AsJob
44 Wait-Job -Job $job
45 Receive-Job $job
46
47 # Succeeds.
48 $job2 = Test-Job -Computer 127.0.0.1 -Retries 6 -AsJob
49 Wait-Job -Job $job2
50 Receive-Job $job2
51
52 # Fails.
53 Test-Job -Computer 127.0.0.0 -Retries 6
54
55 # Succeeds.
56 Test-Job -Computer 127.0.0.1 -Retries 6