powershell - 将 if/else 语句结果输出到格式化表

标签 powershell

我在 Powershell 中编写了一个环境 IP 检查脚本,该脚本可以工作,但我不知道如何在自动调整列大小的格式化表格中将输出显示到屏幕上。

$infile = Import-Csv "~\Env_IPlist.csv" -Delimiter ","
$arr1 = @()

$IP_Addresses = $infile |
                Select-Object "Device_Type", "Device_Name", "IP_Address",
                    "IP_Role", "Location"

Write-Host "Started Ping Test ..."

foreach ($IP in $IP_Addresses) {
    if (Test-Connection $IP.("IP_Address") -Quiet -Count 1 -ErrorAction SilentlyContinue) {
        Write-Host $IP.("Device_Name") ":" $IP.("IP_Address") "Ping successful" -ForegroundColor Green
    } else {
        Write-Host $IP."Device_Name" ":" $IP.("IP_Address") "Ping failed" -ForegroundColor Red -BackgroundColor white
    }
}

Write-Host "Ping Test Completed!"

最佳答案

通过计算属性添加Test-Connection结果,然后通过管道将输出传输到Format-Table

$infile |
    Select-Object Device_Type, Device_Name, IP_Address, IP_Role, Location,
        @{n='Online';e={
            [bool](Test-Connection $_.IP_Address -Quiet -Count 1 -EA SilentlyContinue)
        }} |
    Format-Table -AutoSize

关于powershell - 将 if/else 语句结果输出到格式化表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807251/

相关文章:

powershell - 将命题重命名为目录标题的末尾

c# - 为什么我要使用 Powershell 而不是 C#?

powershell - 尝试通过 powershell : cannot connect to remote server 安装巧克力时出错

c# - 从 cmdlet 中的管道正确获取文件路径

powershell - 如何将 PowerShell 设置为我的 SmartGit "Open Git-Shell"命令?

powershell 包含不工作

powershell - 如何在Powershell Write-Host语句中调用函数

powershell - 在从机上运行 powershell 命令 - Jenkins

powershell - 无法使用Powershell ISE配置TFS构建代理

powershell - 用 Powershell 替换 XML 文件格式文件(.Config 文件)中的行字符串的问题