1

好吧,我对Test-ConnectionPowerShell 中的功能有疑问。我有一个 csv 文件,其中包含列Server nameIPAddress. 我需要使用信息服务器名称IPAddressResult创建连接报告。如何添加有关列服务器名称的信息?

我当前的代码如下所示:

$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
4

2 回答 2

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
于 2018-09-06T13:55:26.293 回答
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
于 2018-09-06T13:44:05.050 回答