简体   繁体   English

PowerShell 大规模测试连接

[英]PowerShell Mass Test-Connection

I am attempting to put together a simple script that will check the status of a very large list of servers.我正在尝试编写一个简单的脚本来检查一个非常大的服务器列表的状态。 in this case we'll call it servers.txt.在这种情况下,我们将其称为servers.txt。 I know with Test-Connection the minimum amount of time you can specify on the -count switch is 1. my problem with this is if you ended up having 1000 machines in the script you could expect a 1000 second delay in returning the results.我知道使用 Test-Connection,您可以在 -count 开关上指定的最短时间是 1。我的问题是,如果您最终在脚本中有 1000 台机器,则返回结果可能会延迟 1000 秒。 My Question: Is there a way to test a very large list of machines against test-connection in a speedy fashion, without waiting for each to fail one at a time?我的问题:有没有一种方法可以快速针对测试连接测试大量机器,而无需等待每台机器一次失败?

current code:当前代码:

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 has a -AsJob switch which does what you want. Test-Connection 有一个 -AsJob 开关,可以满足您的需求。 To achieve the same thing with that you can try:为了达到同样的目的,你可以尝试:

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

Hope that helps!希望有帮助!

I have been using workflows for that.我一直在为此使用工作流程。 Using jobs spawned to many child processes to be usable (for me) .使用产生于许多子进程的作业可用(对我而言)

workflow Test-WFConnection {
  param(
    [string[]]$computers
  )
    foreach -parallel ($computer in $computers) {        
        Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
  }
}

used as用作

Test-WFConnection -Computers "ip1", "ip2"

or alternatively, declare a [string[]]$computers = @() , fill it with your list and pass that to the function.或者,声明一个[string[]]$computers = @() ,用您的列表填充它并将其传递给函数。

Powershell 7 and Foreach-Object -Parallel makes it much simpler now: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM