我正在尝试使用PowerShell中的作业来快速远程访问计算机。我的问题是,这些作业似乎比预期的要花费更多的时间,而且似乎它们是一个接一个地运行,而不是同时运行。如果列表中的最后一台计算机符合要连接的要求,则列表中的27台计算机大约需要40秒钟。这些计算机大多数都处于关闭状态,这就是为什么要花一些时间的原因,但是我希望脚本可以启动所有作业(约3秒),然后同时运行其余命令。似乎仍在按顺序处理作业?想法是能够将其扩展到500台以上的PC(其中大多数不存在或将要关闭)。
$hdusername = Read-Host 'What is your username?'
$hdpassword = Read-Host 'What is your password?' -AsSecureString
$hdpassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($hdpassword))
$computers = $richtextbox1.Text.Split("`n") | % { $_.trim() }
foreach ($computer in $computers)
{
if ($computer -ne "")
{
Start-Job -Name "$computer" -ScriptBlock {
# your commands here, e.g.
Param ([string]$comp,
[string]$User,
[string]$Pass)
if (Test-Connection -ComputerName $comp -quiet -Count 1)
{
$NOTNULLIFLOCKED = $null
$NOTNULLIFLOCKED = gwmi -Class win32_process -computername $comp -Filter "Name='LogonUI.exe'"
if ($NOTNULLIFLOCKED -ne $null)
{
# No Active Session (LogonUI.exe Running)
# If LogonUI.exe is running, that means the login box is currently present on the screen.
# cmdkey is used to store a username and password for a machine so it with autologin
cmdkey /generic:TERMSRV/$comp /user:$User /pass:$Pass
& C:\Windows\System32\mstsc.exe "/v:$comp" "/h:768" "/w:1024"
sleep 1
cmdkey /delete:TERMSRV/$comp
}
}
} -ArgumentList $computer, $hdusername, $hdpassword | out-null
}
}