[pre]
$ScriptBlock = {
Param (
$Vm,
$vc,
$session)
$VCenter = Connect-VIServer -Server $vc -session $session -force
$status = Get-VM $Vm
Write-host $status.Name
if ($status.PowerState -eq “PoweredOff”)
{
$Clone = ‘_2.2’
$NewVM = $Vm + $Clone
Write-host $NewVM
}
}
$Results = @()
$Throttle = 5 #threads
$sesssionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$sesssionstate.ImportPSModule(“Vmware.VimAutomation.Core”)
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, $Throttle, $sesssionstate, $host)
$RunspacePool.Open()
$Jobs = @()
$Vms = gc .\vmlist.txt
Foreach ($Vm in $Vms)
{
#Start-Sleep -Minutes 1
$Job = [powershell]::Create().AddScript($ScriptBlock).AddArgument($Vm).AddArgument($con.Name).AddArgument($con.SessionId)
$Job.RunspacePool = $RunspacePool
$Jobs += New-Object PSObject -Property @{
Job = $Job
Result = $Job.BeginInvoke()
}
}
while ($Jobs -Contains $false){}
foreach($Job in $jobs)
{
$results+=$Job.Job.EndInvoke($job.Result)
$Job.Job.Dispose()
}
$results
[/pre]
Input :
======
INTCL2K8
INTCL2K82
INTCL2k83
Output:
=============
PS C:\Users\Administrator\Desktop> .\tests.ps1
INTCL2K8
INTCL2K8_2.2
INTCL2K82
INTCL2K82_2.2
INTCL2k83
INTCL2K83_2.2
PS C:\Users\Administrator\Desktop> .\tests.ps1
INTCL2K82
INTCL2K8
INTCL2K82_2.2
INTCL2K8_2.2
INTCL2k83
INTCL2K83_2.2
PS C:\Users\Administrator\Desktop> .\tests.ps1
INTCL2K82
INTCL2K8
INTCL2k83
INTCL2K82_2.2
INTCL2K8_2.2
INTCL2K83_2.2
My understanding is runspace take input sequentially and run separately.but the output is not sequential. is it because of runtime different and output which one complete first?
The second doubt is how the output “_2.2” VMs comes after one if the thread is running independently. is the code wrong?
the output should be always like this
INTCL2K8
INTCL2K8_2.2
INTCL2K82
INTCL2K82_2.2
INTCL2k83
INTCL2K83_2.2