从文本文档的每一行检索两个值

时间:2017-03-30 15:15:41

标签: powershell

我正在尝试从文件,ping结果和描述中获取内容。通过ping的一切工作,但我如何获得输出中的描述?

GC D:\Temp\System.txt | %{
    If (Test-Connection $_ -Quiet -Count 2){
        Write-Host "$_ is UP" -b Green
    }
    Else{
        Write-Host "$_ is Down" -b Red
    }
}
PAUSE

包含要ping的IP地址及其说明的内容

10.200.11.2     Firewall
10.200.11.14    Test1
192.168.254.81  Test2
192.168.254.133 Test3

2 个答案:

答案 0 :(得分:1)

使用正则表达式($_ -replace "\s.+","") - 所有直到空格(制表) ($_ -replace ".+\s","") - 空格后的所有内容(制表)

  GC D:\Temp\System.txt | %{
If (Test-Connection ($_ -replace "\s.+","") -Quiet -Count 2){
    Write-Host "$_ is UP" -b Green
    Write-Host ($_ -replace ".+\s","")
}
Else{
    Write-Host "$_ is Down" -b Red
    Write-Host ($_ -replace ".+\s","")
}

字符串Write-Host ($_ -replace ".+\s","")是描述

答案 1 :(得分:0)

要添加其他几种方法:

由于看起来您正在使用制表符分隔符,因此可以在选项卡上进行拆分。

GC D:\Temp\System.txt | % {
    $hostname = ($_.Split("`t") | ? {$_ -ne ""})[0]
    $description = ($_.Split("`t") | ? {$_ -ne ""})[1]
    If (Test-Connection $hostname -Quiet -Count 2) {
        Write-Host "Hostname: $hostname Description: $description is UP" -b Green
    } Else {
        Write-Host "Hostname: $hostname Description: $description is Down" -b Red
    }
}

或者您可以将其导入为带有制表符分隔符的CSV

Import-CSV D:\Temp\System.txt -Delimiter `t -Header hostname,description | % {
    If (Test-Connection $_.hostname -Quiet -Count 2) {
        Write-Host "Hostname: $($_.hostname) Description: $($_.description) is UP" -b Green
        [pscustomobject]@{
            Hostname = $_.hostname
            Description = $_.description
            Status = "Up"
        }
    } Else {
        Write-Host "Hostname: $($_.hostname) Description: $($_.description) is Down" -b Red
        [pscustomobject]@{
            Hostname = $_.hostname
            Description = $_.description
            Status = "Down"
        }
    }
} | ConvertTo-HTML | Out-File D:\Temp\Example.html