如何将结果导出到.csv?服务器名称作为第一列,联机/脱机作为第二列



>我正在尝试将powershell的结果导出为csv,第一列为$server,第二列为在线/离线。实际上,我想定义许多列。我认为这是一个良好的开端。请让我知道如何实现这一目标。

$ErrorActionPreference = 'SilentlyContinue'
$ServerName = "TDL498", "TDL498123", "TDL498456"
foreach ($Server in $ServerName)
{
    if (test-Connection -ComputerName $Server -Count 2 -Quiet)
    {
        write-Host "$Server Online" -ForegroundColor Green 
    }
    else
    {
        Write-Host "$Server Offline"
    }
} 
你可以

通过创建一个PSCustomObject来做到这一点。[grin] 据我所知,无需使用 Test-Connection cmdlet 设置任何特殊的错误处理,因为它返回了使用 -Quiet 参数进行连接测试的False/True

$ComputerNameList = @(
    'LocalHost'
    '10.0.0.1'
    '127.0.0.1'
    'BetterNotBeThere'
    $env:COMPUTERNAME
    )
$Results = foreach ($CNL_Item in $ComputerNameList)
    {
    [PSCustomObject]@{
        ComputerName = $CNL_Item
        Online = Test-Connection -ComputerName $CNL_Item -Count 1 -Quiet
        }
    }
# on screen
$Results
# to csv file
$Results |
    Export-Csv -LiteralPath "$env:TEMPMuhammadSuhailAsrulsani_ComputerStatus.csv" -NoTypeInformation

输出到屏幕...

ComputerName     Online
------------     ------
LocalHost          True
10.0.0.1          False
127.0.0.1          True
BetterNotBeThere  False
[MySysName]        True

CSV 文件内容...

"ComputerName","Online"
"LocalHost","True"
"10.0.0.1","False"
"127.0.0.1","True"
"BetterNotBeThere","False"
"[MySysName]","True"

最新更新