Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops Ping主机名列表并将结果输出到powershell中的csv_Loops_Powershell_Csv_Ping - Fatal编程技术网

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

Loops Ping主机名列表并将结果输出到powershell中的csv,loops,powershell,csv,ping,Loops,Powershell,Csv,Ping,我有一个很大的主机名列表,我需要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 Gre

我有一个很大的主机名列表,我需要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"
  }
}

另外,您还可以使用创建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"

这是一个稍微干净一点,包括原来的前景选项,但顺便说一句,“延迟”开关似乎被忽略了-PB

我会这样做。使用一系列计算机和作业非常有效。如果主机已启动,则Responsetime属性将为非null

$names = Get-content hnames.txt
test-connection $names -asjob -count 1 | recieve-job -wait -auto

好极了!这管用!有没有办法让脚本本身打印到csv文件而不是管道?我需要将此内容交给我的一位同事,他希望只运行脚本。是的,您可以使用
Add Content
cmdlet而不是Write host cmdlet,例如
Add Content output.csv“$name,up”
现在有了编写
CSV
的函数,并且——为了记录Ping,我发现使用
json
更容易,比如:
测试连接-TargetName$targets-Ping-OutVariable Ping\u结果$ping|u results | ConvertTo Json-AsArray-Compress-OutVariable last|u export | Out File-FilePath“log.Json”-Append顺便说一句,Powershell 6的测试连接超时选项“延迟”选项错误。'“延迟”不起任何作用,先前的定时选项不再存在。。。因此,您将以最大速度ping。。。。PB
$names = Get-content hnames.txt
test-connection $names -asjob -count 1 | recieve-job -wait -auto