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

问题描述 投票:0回答:5

我有一个很大的主机名列表,我需要 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 文件,但我不知道该怎么做。

请帮忙!

loops powershell csv ping
5个回答
15
投票

您可以使用以下代码(我只是将 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"
  }
}

附注您还可以使用 Out-File Cmdlet 创建 CSV 文件


4
投票

我是 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"

1
投票

我会这样做。使用计算机列表和 -asjob 效果非常好。如果主机启动,则 Responsetime 属性(令人困惑的是标头是“Time(ms)”)将为非空。

$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

最近我就是这样做的。它需要在 powershell 5.1 中安装 threadjobs。或者只使用 get-port。我将其粘贴在 $env:psmodulepath 中的 mymod\mymod.psm1 模块文件中。我可以在 10 秒内查看教室。

function get-pport {  # multi-threaded
  param($list)
  
  $list |
    % { $_ | start-threadjob { get-port $input } -throttlelimit 20 } |
    receive-job -wait -auto
}

function Get-Port {

  Param (
    [parameter(ValueFromPipeline)]
    [string[]]$Hostname='yahoo.com'
  )
  
  begin {   
    $ports = 22,5988,3389,5985
    $ping = New-Object System.Net.Networkinformation.ping
    $Timeout = 200 # ms 
  }

  process {
    $hostname | foreach {
      $openPorts = @()
  
      foreach ($port in $ports) {
        $client = New-Object System.Net.Sockets.TcpClient
        $beginConnect = $client.BeginConnect($_,$port,$null,$null)
        Start-Sleep -Milli $TimeOut
        if($client.Connected) { $openPorts += $port }
        $client.Close()
      }
  
      $result = $Ping.Send($_, $timeout)
      if (! $result) { write-error "hostname $_ not found" }
      $pingstatus = ($result.status -eq 'Success')
  
      New-Object -typename PSObject -Property @{
        HostName = $_
        Port = $openPorts
        Ping = $pingstatus 
      } | select hostname,port,ping
    } # end foreach
  } # end process

}

示例:

$avid = cat afile.txt
pport $avid

HostName Port          Ping
-------- ----          ----
A006     {3389, 5985}  True
A011     {3389, 5985}  True
A015     {3389}        True

0
投票
    $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


0
投票

所以我修改了 @js2010 答案来检查端口列表和 ICMP ping。如果端口或 ICMP ping 返回,则设置状态。还可以通过仅执行而不是在执行时传递文件来将其设置为运行。

function get-pport {

    # Define the file path containing the URLs
    $urlFile = "hnames.txt"
    $outputFile = "port_scan_results.csv"
    
    # Define the list of ports
    $ports = @(22, 443, 80)

    # Read URLs from the file
    $urls = Get-Content $urlFile
    
    $results = @()

    $urls | ForEach-Object {
        $url = $_
        $openPorts = @()

        # Perform ICMP ping
        try {
            $ping = New-Object System.Net.NetworkInformation.Ping
            $pingResult = $ping.Send($url)

            if ($pingResult.Status -eq 'Success') {
                $status = "up"
            } else {
                $status = "down"
            }
        } catch {
            Write-Host "Error: ICMP ping failed for $url - $_"
            $status = "down"
        }

        # Check for open ports
        foreach ($port in $ports) {
            $client = New-Object System.Net.Sockets.TcpClient
            $ar = $client.BeginConnect($url, $port, $null, $null)
            $wait = $ar.AsyncWaitHandle.WaitOne(200, $false)

            if ($wait -and !$ar.IsCompleted) {
                $client.Close()
            }
            else {
                if ($client.Connected) {
                    $openPorts += $port
                }
                $client.Close()
            }
        }

        if ($openPorts -and $status -eq "down") {
            $status = "up"
        }

        $result = New-Object -TypeName PSObject -Property @{
            HostName = $url
            Port = $openPorts -join ','
            Status = $status
        }

        $results += $result
    }

    # Export results to CSV
    $results | Export-Csv -Path $outputFile -NoTypeInformation
}

# Run the function
get-pport
© www.soinside.com 2019 - 2024. All rights reserved.