【问题标题】:Powershell: Formatting Select -Index arrayPowershell:格式化选择-索引数组
【发布时间】:2014-07-25 00:16:36
【问题描述】:

我试图想出一种格式化解析行输出的好方法,使用以下数据作为我实际搜索的行之一,以便解析出一些数据。

#Data from my File
2014-07-24 19:30:23 IP.ADD.RESS.# GET /:8888/xxx/update/status/CheckingForUpdates - 80 - 192.168.x.x - 400 0 0 15

所以我正在做的是在一个大文件中搜索这样的行。我实际上是在搜索 CheckingForUpdates 的关键字,然后通过执行以下 select-string 行将“xxx”和“192.168.x.x”分开。

Select-String -path $FileLocation -Pattern "CheckingForUpdates" -AllMatches |
%{$_ -split"/"} | %{$_ -split"- "} | Select -Index 2,7 

这样我会得到一个输出:

xxx
192.168.x.x

所以我的问题是,当我处理来自我正在使用的实际文件的 100 个输出时,有人知道我可以创建一种易于阅读的格式吗?我希望的是

项目 xxx 正在使用,IP 地址为 192.168.x.x

我尝试了 Write-Output,但由于尝试在一行中使用 Select -Index 两次而失败。 Powershell 似乎根本不喜欢这样。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    使用您的示例数据,您会得到一个字符串数组输出。在我的回答中,我将该字符串数组分配给一个变量并使用-f 格式参数格式化输出。

    $data = "2014-07-24 19:30:23 IP.ADD.RESS.# GET /:8888/xxx/update/status/CheckingForUpdates - 80 - 192.168.x.x - 400 0 0 15"
    $strings = $data | Select-String -Pattern "CheckingForUpdates" -AllMatches |
    %{$_ -split"/"} | %{$_ -split"- "} | Select -Index 2,7
    "Item {0} is using and IP Address of {1}" -f $strings[0],$strings[1]
    

    这给了我们以下输出:

    $data = "2014-07-24 19:30:23 IP.ADD.RESS.# GET /:8888/xxx/update/status/CheckingForUpdates - 80 - 192.168.x.x - 400 0 0 15"
    $strings = $data | Select-String -Pattern "CheckingForUpdates" -AllMatches |
    %{$_ -split"/"} | %{$_ -split"- "} | Select -Index 2,7
    
    Item xxx is using and IP Address of 192.168.x.x 
    

    虽然我们不必使用-f,但它确实会清理代码以使其更易于阅读。有关它的更多信息可以找到here

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 2020-01-22
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多