[英]PowerShell Mass Test-Connection
我正在嘗試編寫一個簡單的腳本來檢查一個非常大的服務器列表的狀態。 在這種情況下,我們將其稱為servers.txt。 我知道使用 Test-Connection,您可以在 -count 開關上指定的最短時間是 1。我的問題是,如果您最終在腳本中有 1000 台機器,則返回結果可能會延遲 1000 秒。 我的問題:有沒有一種方法可以快速針對測試連接測試大量機器,而無需等待每台機器一次失敗?
當前代碼:
Get-Content -path C:\Utilities\servers.txt | foreach-object {new-object psobject -property @{ComputerName=$_; Reachable=(test-connection -computername $_ -quiet -count 1)} } | ft -AutoSize
Test-Connection 有一個 -AsJob 開關,可以滿足您的需求。 為了達到同樣的目的,你可以嘗試:
Get-Content -path C:\\Utilities\\servers.txt | 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 }}} | ft -AutoSize
希望有幫助!
我一直在為此使用工作流程。 使用產生於許多子進程的作業可用(對我而言) 。
workflow Test-WFConnection {
param(
[string[]]$computers
)
foreach -parallel ($computer in $computers) {
Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
}
}
用作
Test-WFConnection -Computers "ip1", "ip2"
或者,聲明一個[string[]]$computers = @()
,用您的列表填充它並將其傳遞給函數。
Powershell 7 和Foreach-Object -Parallel
現在使它變得更簡單:
Get-Content -path C:\Utilities\servers.txt | ForEach-Object -Parallel {
Test-Connection $_ -Count 1 -TimeoutSeconds 1 -ErrorAction SilentlyContinue -ErrorVariable e
if ($e)
{
[PSCustomObject]@{ Destination = $_; Status = $e.Exception.Message }
}
} | Group-Object Destination | Select-Object Name, @{n = 'Status'; e = { $_.Group.Status } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.