Test-NetConnection -AsJob?



我是否可以利用Test-NetConnection -ComputerName $_ -Port 5985而不是Test-Connection -ComputerName $_ -Count 1 -AsJob的这段代码?我不能用Test-NetConnection命令来使用-AsJob。有什么变通办法吗?

下面是我的代码:
$online = @()
$pc = Get-Content C:servers.txt 
$pc | ForEach-Object { 
Test-Connection -ComputerName $_ -Count 1 -AsJob 
} | Get-Job | Receive-Job -Wait | 
Select-Object @{Name='ComputerName';Expression={$_.Address}},@{Name='Reachable';Expression={
if ($_.StatusCode -eq 0) { 
$true 
} else { 
$false 
}
}} | ForEach-Object {
if ($_.Reachable -eq $true) {
$online += $_.ComputerName
}
}
$online | ft -AutoSize

servers.txt基本上包含了网络上所有机器的主机名。

对于普通的Windows PowerShell 5.1,你能得到的最好的是使用RunspacePool,代码不容易遵循,并且有一个很好的理由,在PowerShell中有许多可用的模块来处理多线程。最推荐的是ThreadJob.
这个答案提供了一个"copy-pastable">版本的函数,可以处理多线程从管道类似于ForEach-Object -Parallel,但兼容Windows PowerShell 5.1。

$ProgressPreference = 'Ignore'
$maxThreads = 32 # How many jobs can run at the same time?
$pool = [runspacefactory]::CreateRunspacePool(1, $maxThreads,
[initialsessionstate]::CreateDefault2(), $Host)
$pool.Open()
$jobs = [System.Collections.Generic.List[hashtable]]::new()
Get-Content C:servers.txt | ForEach-Object {
$instance = [powershell]::Create().AddScript({
param($computer)
[pscustomobject]@{
Computer = $computer
Port     = 5985
PortOpen = Test-NetConnection $computer -Port 5985 -InformationLevel Quiet
}
}).AddParameters(@{ computer = $_ })
$instance.RunspacePool = $pool
$jobs.Add(@{
Instance = $instance
Async    = $instance.BeginInvoke()
})
}
$result = while($jobs) {
$job = $jobs[[System.Threading.WaitHandle]::WaitAny($jobs.Async.AsyncWaitHandle)]
$job.Instance.EndInvoke($job.Async)
$job.Instance.Dispose()
$null = $jobs.Remove($job)
}
$pool.Dispose()
$result | Where-Object PortOpen # filter only for computers with this port open

最新更新