
Multithreads in Powershell
A heavy Powershell script uses a lot of ram to proceed. There are many ways to avoid that, and also avoid crashes of the server launching that. The easiest way is to use multithreads with job.
Using jobs will open a new thread into your server/remote server to execute a part of the script. Jobs also can be called to work at the same time, reducing the global execution time of the script.
Here below a small script to introduce you using jobs :
Start-Job {Get-Process} Get-Job | Wait-Job Get-Job | Receive-Job
In another thread, a Powershell one, a simple command is launch to get all running processes.
The “Wait-Job” command will force the script to wait for the job to end .
The “Receive-Job” will display what’s on the “screen” of that job, here all running processes.
The “Start-Job” command has some interesting parameters, such as “-Name” that allows you to use a familiar name to follow your job. You can also write down a full script using the “-ScriptBlock” parameter, also including the “-Arguments” parameter to use your script variable.
$text="Hello World !!" Start-Job -Name "Hello" -ScriptBlock{Write-host "$args"} -Arguments $text Receive-Job -Name "Hello" Hello World Remove-Job -Name "Hello"
Never forget to remove a job you don’t need anymore using the “Remove-Job” command !
Links :
PowerShell Class:
http://msdn.microsoft.com/en-us/library/system.management.automation.powershell%28v=vs.85%29.aspx
PowerShell AddParameter Method: