In My Previous post on Runspace in windows PowerShell I talked about the basics of the using runspace in windows PowerShell, where we learn how we can create a Runspace and pass on the script block to run the same in the back ground, well that was a simple script block we used, today we will take it one step further, and will see how we can use parameters available in our script within the windows PowerShell Runspace.
If you haven’t go through my first post on runspace please below.
Post 1 - Working with RunSpace in Powershell
So Let’s Use the code from yesterday’s lesion to setup a Runspace Quickly.
#Create RunSpace
$Runspace=[runspacefactory]::CreateRunspace()
$Runspace.Open()
#Create a New job
$Job=[System.Management.Automation.PowerShell]::Create()
$job.runspace=$Runspace
So now when we have runspace created lets now create some sample script with parameters.
#Script Block With Parameters
$ScriptBlock={
param ($CPU = 10)
get-process | ? {$_.CPU -gt $CPU}
}
So lets add the Script Block and Parameters to our RunSpace.
We can use “AddArgument” method available to specify the parameters available in the script.
Note: if you have more than one parameters in the script make sure to add then in the order.
[Void]$job.AddScript($scriptBlock)
[Void]$job.AddArgument($CPU)
Now we have added the argument, so we are ready to invoke our runspace.
$JobStatus=$job.BeginInvoke()
Next Run the $jobStatus to check if the Job has been completed.
As we see the “IsCompleted” is showing True, we can now run the "EndInvoke" method to get the data back.
$Data=$job.EndInvoke($JobStatus)
$job.Dispose()
That’s it from today’s post, tomorrow we will see how we can do multithreading in the runspace.
Below is the full code used in this post.
#Create RunSpace
$Runspace=[runspacefactory]::CreateRunspace()
$Runspace.Open()
#Create a New job
$Job=[System.Management.Automation.PowerShell]::Create()
$job.runspace=$Runspace
#Script Block With Paramiters
$ScriptBlock={
param ($CPU = 10)
get-process | ? {$_.CPU -gt $CPU}
}
[Void]$job.AddScript($scriptBlock)
[Void]$job.AddArgument($CPU)
$JobStatus=$job.BeginInvoke()
$Data = $job.EndInvoke($JobStatus)
$job.Dispose()
$data
Comments
Post a Comment