我正在嘗試拖動的腳本有點不知所措。Powershell運行空間將不會執行
簡而言之:我想掃描我的域計算機的WinRM連接 - 我可以做到這一點很好。問題是,它需要5分鐘才能完成 - 這就是爲什麼我想要多線程的任務。
工作的非多線程代碼:
# this is normaly a textfile with lots of machine hostnames
$computers = "PC100","PC106","PC124","PC115","PC21"
function checkMachine($computers){
$ErrorActionPreference = "Stop"
foreach ($item in $computers){
#the function contest only performs a ping and returne $true or $false
$connection = ConTest($item)
if($connection){
try{
$winRM = test-wsman -ComputerName $item
if($winRM){
write-host "winRM"
[void] $objListboxLeft.Items.Add($item)
}
}catch{
write-host "NO winRM"
[void] $objListboxCenter.Items.Add($item)
}
}else{
write-host "offline"
[void] $objListboxRight.Items.Add($item)
}
}
}
這基本上是什麼我不skript /會做只是一小部分,但它是需要年齡的一部分。
我失敗的運行空間測試 - 我基本上沒有得到任何結果。沒有文本框,我的命令行沒有輸出,我基本上不知道我做錯了什麼。
多線程代碼:
function MulticheckMachine($computers){
$ErrorActionPreference = "Stop"
$runspaceCollection = @()
$runspacePool = [RunspaceFactory]::CreateRunspacePool(1,5)
$runspacePool.open()
$scriptBlock = {
Param($item)
$connection = ConTest($item)
if($connection){
try{
test-wsman -ComputerName $item
$winRM = test-wsman -ComputerName $item
if($winRM){
write-host "winRM"
[void] $objListboxLeft.Items.Add($item)
}
}catch{
write-host "NO winRM"
[void] $objListboxCenter.Items.Add($item)
}
}else{
write-host "offline"
[void] $objListboxRight.Items.Add($item)
}
}
Foreach($item in $computers){
$powershell = [PowerShell]::Create().AddScript($scriptBlock).AddArgument($item)
$powershell.runspacePool = $runspacePool
[Collections.Arraylist]$runspaceCollection += New-Object -TypeName PSObject -Property @{
Runspace = $powershell.BeginInvoke()
PowerShell = $powershell
}
$runspaceCollection
}
While($runspaceCollection){
Foreach($runspace in $runspaceCollection.ToArray()){
If($runspace.Runspace.IsCompleted){
$runspace.PowerShell.EndInvoke($runspace.Runspace)
$runspace.PowerShell.Dispose()
$runspaceCollection.Remove($runspace)
}
}
}
}
運行空間代碼來自這些指南的混合:
http://newsqlblog.com/2012/05/22/concurrency-in-powershell-multi-threading-with-runspaces/
我希望有人能幫助我,並告訴我在哪裏/爲什麼我失敗了。謝謝!
'$ objListboxLeft','$ objListboxCenter'和'$ objListboxRight'不運行空間存在,這可能就是它的失敗。從ScriptBlock返回一個對象 –
我想你可以通過使用[powershell jobs](https://technet.microsoft.com/en-us/library/hh847805.aspx)來簡化你的腳本。類似'invoke-command -computername $ computers -scriptblock {#check winrm localy} -asjob' –
@Kayasax仍然無法解決他嘗試修改執行範圍/ runspace/process中不存在的對象的問題 –