大规模测试连接Powershell

时间:2018-09-06 12:54:31

标签: powershell csv psobject

好,我在PowerShell中使用Test-Connection函数时遇到问题。 我有一个csv文件,其列为Server nameIPAddress。我需要使用信息服务器名称 IPAddress 结果创建连接报告。如何添加有关列服务器名称的信息?

我当前的代码如下:

$Report = @()
$Servers = Import-CSV "C:\skrypt\bobi\servers.csv"  -Delimiter ';'
foreach ($Server in $Servers) {
    if ($Alive = Test-Connection -ComputerName $Server.IPAddress -Count 1 -quiet) {
        $TestResult = New-Object psobject -Property @{
            IPAddress = $Server.IPAddress
            Result    = "Online"
        }
    }
    else {
        $TestResult = New-Object psobject -Property @{
            IPAddress = $Server.IPAddress
            Result    = "Offline"
        }
    }
    $Report += $TestResult
}       
$Report | Select-Object IPAddress, Result | Export-Csv C:\skrypt\bobi\Report.csv -nti

2 个答案:

答案 0 :(得分:0)

我认为这可能对您有所帮助

$Servers = @(
    [PSCustomObject]@{
        'Server Name' = 'Server1'
        IPAddress = '10.10.10.10'
    }
    [PSCustomObject]@{
        'Server Name' = 'Wrong'
        IPAddress = '10.10.10.999'
    }
    [PSCustomObject]@{
        'Server Name' = 'Server2'
        IPAddress = '10.10.10.15'
    }
)

$Report = foreach ($Server in $Servers) {
    # First we collect all details we know in an object
    $Result = [PSCustomObject]@{
        Name   = $Server.'Server Name'
        IP     = $Server.IPAddress
        Online = $false
    }

    # Then we do the test
    if (Test-Connection -ComputerName $Server.IPAddress -Count 1 -Quiet) {
        # If the connection is successful, we set it to True
        $Result.Online = $true    
    }

    # As a last step we return the complete object
    # where it is collected in the array of Report
    $Result
}

$Report | Select-Object Name, IP, Online

答案 1 :(得分:0)

如果您的CSV文件具有带有主机名的列,则需要将PSCustomObject更改为:

$TestResult = New-Object psobject -Property @{
    IPAddress = $Server.IPAddress
    HostName = $Server.HostName #assuming column name is "HostName"
    Result    = "Result"
}

如果您的CSV文件没有带有主机名的列,则您需要使用其System.Net.Dns方法请求GetHostByAddress类。像这样:

$TestResult = New-Object psobject -Property @{
    IPAddress = $Server.IPAddress
    HostName = $([System.Net.Dns]::GetHostByAddress($Server.HostName).HostName -join ';')
    Result    = "Result"
}

在两种情况下,您都需要使用管道的HostName属性来导出csv文件

$Report | Select-Object IPAddress, HostName, Result | Export-Csv C:\skrypt\bobi\Report.csv -nti