Multi-Thread in PowerShell

This command allow to launch the same script many times at the same time.

In this example, $serverslist contains 4 server names that the cmdlet invoke-command will send in argument to  myscript.ps1, the –asjob parameter will free us of the sequential processing time of each execution of the invoke-command (just see the screenshot below)

$serverslist = “c:scriptsserverslist.txt”

$serverslist | foreach-object {

 $server=$_

invoke-command -computername mon_serveur -filepath “c:scriptsmyscript.ps1″ -ArgumentList $server -asjob -JobName $server

}

get-job can control the job status. Here below we have 4 jobs that launch the same command because the file « c:scriptsservers list.txt » contains 4 server names.

receive-job display the default output of a job (an error, a write-host etc …). To keep that output, you have to use the -keep argument. Else, the output will be lost !

You can launch more than 5 jobs at the same time with that command :

cd WSMan:localhostShell
set-Item .MaxShellsPerUser 50

 

Leave a comment