Ping 主机名列表并将结果输出到 powershell 中的 csv

Ping a list of host names and output the results to a csv in powershell

我有一大堆主机名,需要 ping 以查看它们是正常运行还是异常运行。我不太擅长编写脚本,但我设法弄清楚了这一点:

$names = Get-content "hnames.txt"

foreach ($name in $names){
  if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
    Write-Host "$name is up" -ForegroundColor Green
  }
  else{
    Write-Host "$name is down" -ForegroundColor Red
  }
}

这让我得到了我需要的东西,但我现在需要将这些结果写到一个 csv 文件中,但我不知道该怎么做。

请帮忙!

您可以改用以下代码(我只是将写入主机调用更改为 CSV 格式)并使用 "PowerShell.exe script.ps > output.csv" 执行它 请注意,您必须从包含 hnames.txt 的文件夹中执行它,或者只需将 "hnames.txt" 更改为完整路径。

$names = Get-content "hnames.txt"

foreach ($name in $names){
  if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
    Write-Host "$name,up"
  }
  else{
    Write-Host "$name,down"
  }
}

P.S。您还可以使用 Out-File Cmdlet 创建 CSV 文件

我是 Powershell 的新手,所以我把它作为一项学习任务,因为我需要一种快速简单的方法来检查 PC 列表的 up/down 状态。需要进行这些调整才能使其干净地输出到屏幕和 txt 文件

$Output= @()
$names = Get-content "hnames.txt"
foreach ($name in $names){
  if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
   $Output+= "$name,up"
   Write-Host "$Name,up"
  }
  else{
    $Output+= "$name,down"
    Write-Host "$Name,down"
  }
}
$Output | Out-file "C:\support\result.csv"
    $Output= @()
    $names = Get-Content ".\input\Servers.txt"
    foreach ($name in $names){
      if (Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue -quiet){
       $Output+= "$name,up"
       Write-Host "$Name,up" -ForegroundColor Green
      }
      else{
        $Output+= "$name,down"
        Write-Host "$Name,down" -ForegroundColor Red
      }
    }
    $Output | Out-file ".\output\result.csv"

这有点干净,包括原始的前景选项,但是,顺便说一句,'delay' 开关似乎被忽略了 -PB

我会这样做。使用计算机列表和 -asjob 效果很好。如果主机启动,响应时间 属性(令人困惑的是 header 是“时间(毫秒)”)将是 non-null。

$names = Get-content hnames.txt
test-connection $names -asjob -count 1 | receive-job -wait -auto
Source        Destination     IPV4Address      IPV6Address     Bytes    Time(ms)
------        -----------     -----------      -----------     -----    --------
COMP001       yahoo.com       74.6.231.21                      32       39
COMP001       microsoft.com   40.113.200.201                   32