Execute PowerShell Script Asynchronously


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

Parent.ps1
$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) 
[void]$runspacePool.Open()
$ps = [PowerShell]::Create()
$ps.RunSpacePool = $runspacePool
[void]$ps.AddScript($cmd)
$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
$ps.EndInvoke($ret)

#termination
$ps.Dispose()
$runspacePool.Close()


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

Child.ps1
#arguments
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.

ParentRemote.ps1
#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
Profile
I have technical job experience in enbedded software development and server side infrastructure/application engineering. I'm interested in programming and computer security.
Objective
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.
Link
  • LinkedIn (preparing)

  • Twitter

  • Facebook (preparing)

  • GitHub

  • StackOverFlow (preparing)

Archives