Execute PowerShell Script Asynchronously

By creating RunSpacePool, the multi thread script call is available. The followings codes show multi thread execution on powershell.

$dir = "d:\work"
$cmd = $dir + "child.ps"
$cmd += (' "' + "I" + '"')
$cmd += (' "' + "am" + '"')
$cmd += (' "' + "child" + '"')

#create runspace pool
#specify number of pool min and max
$runspacePool = [RunspaceFactory]::CreateRunspacePool(1, 10) 
$ps = [PowerShell]::Create()
$ps.RunSpacePool = $runspacePool
$ret = $ps.BeginInvoke()
#do someting in parent thread
if($ret.isCompleted -eq $False){
    #wait for child thread to finish.
    Start-Sleep -Milliseconds 100
#this is return code


A example of called script. The script argments are available. The processing result can be passed to parent as return value.

Param($arg1, $arg2, $arg3)

#do something in child thread
echo ($arg1 + " " + $arg2 + " " + $arg3 + ".") > "another_thread.txt"

#return code
return 0

By preparing user account credential on remote machine, the codes in child thread are executed in the remote session.

#create remote connection information
$remoteInfo = New-Object System.Management.Automation.Runspaces.WSManConnectionInfo
$remoteInfo.Credential = $cred		
$remoteInfo.ComputerName = $server

#create runspace pool on remote server
$runspacePool = [RunspaceFactory]::CreateRunspacePool(1, 10, $remoteInfo) #min and max
I have technical job experience in enbedded software development and server side infrastructure/application engineering. I'm interested in programming and computer security.
To write down my technical knowledge in the place where I can access from anywhere. To share my program source code. To train my writing skill.
  • LinkedIn (preparing)

  • Twitter

  • Facebook (preparing)

  • GitHub

  • StackOverFlow (preparing)