Ping主机名列表并将结果输出到Powershell中的CSV [英] Ping a list of host names and output the results to a csv in powershell

查看:273
本文介绍了Ping主机名列表并将结果输出到Powershell中的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的主机名列表,我需要对其进行ping操作以查看它们是启动还是关闭.我并不是真的擅长脚本编写,但是我设法弄清楚了这一点:

I have a large list of hostnames I need to ping to see if they are up or down. I'm not really that great at scripting but I managed to figure this much out:

$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文件中,我不知道该怎么做.

This gets me what I need but i now need to write out these results to a csv file and i have no idea how to do that.

请帮助!

推荐答案

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

You can use the following code instead (I simply altered the write-host calls to CSV formatting) and execute it with "PowerShell.exe script.ps > output.csv" Note that you must execute it from the folder that contains hnames.txt, or simply change the "hnames.txt" to a full path.

$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.您还可以使用文件外Cmdlet 创建CSV文件

P.S. You can also use the Out-File Cmdlet to create the CSV file

这篇关于Ping主机名列表并将结果输出到Powershell中的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆