簡體   English   中英

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 文件中,我不知道該怎么做。

請幫忙!

您可以改用以下代碼(我只是將 write-host 調用更改為 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"
  }
}

PS 您還可以使用Out-File Cmdlet創建 CSV 文件

我完全是 Powershell 的新手,所以我把它作為一項學習任務,因為我需要一種快速而簡單的方法來檢查 PC 列表的啟動/關閉狀態。 需要進行這些調整才能將其干凈地輸出到屏幕和 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"

這有點干凈,包括原始的前景選項,但順便說一句,“延遲”開關似乎被忽略了 -PB

我會這樣做。 使用計算機列表和 -asjob 效果很好。 如果主機啟動,響應時間屬性(令人困惑的標題是“時間(毫秒)”)將為非空。

$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM