![](/img/trans.png)
[英]Powershell 2.0 Ping list of computers and send email on failure
[英]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.