【问题标题】:Get object from a file using Powershell使用 Powershell 从文件中获取对象
【发布时间】:2021-11-29 15:52:49
【问题描述】:

我有一个名为 inputs.txt 的纯文本文件,其内容如下:

some_array = {
  "x" = "blabla1"
  "y" = "blabla2"
  "z" = "blabla3"
}
ip_addresses = {
  "x" = "1.2.3.4"
  "y" = "1.2.3.4"
  "z" = "1.2.3.4"
}
names = {
  "x" = "abc"
  "y" = "def"
  "z" = "ghi"
}

...以及更多相同类型的数组。

现在我需要使用 PowerShell 来遍历对象 ip_addresses 中的 IP 地址。

我真的不会比:

$file = Get-Content -Path ./inputs.txt

这将返回整个文件,但我只需要 IP 地址。最好用逗号分隔。

有没有一种简单的方法来循环这个?如果 input.txt 是 json 文件会更容易,但不幸的是它们不是。这是结构,不能更改。

提前感谢您的帮助!

【问题讨论】:

  • 您不能将inputs.txt 格式化为JSON 或XML 吗?这可能会让生活更轻松......

标签: powershell loops


【解决方案1】:

我会为此使用switch

$collectIPs = $false
$ipAddresses = switch -Regex -File 'D:\Test\inputs.txt' {
    '^ip_addresses\s*=' { $collectIPs = $true }
    '^}' {$collectIPs = $false }
    default {
        if ($collectIPs) { ($_ -split '=')[-1].Trim(' "') }
    }
}

$ipAddresses -join ', '

输出:

1.2.3.4, 1.2.3.4, 1.2.3.4

【讨论】:

    【解决方案2】:

    当然Json 会更容易。

    $start = $false
    $IPs = Get-Content -Path ./inputs.txt | ForEach-Object {
        if ($_ -match "}") {
            $start = $false
        }
    
        if ($start) {
            $arr = $_ -split "="
            $Name = ($arr[0] -replace '"', '').Trim()
            $Value = ($arr[1] -replace '"', '').Trim()
            New-Object -TypeName PSObject -Property @{Name=$Name; IP=$Value}
        }
    
        if ($_ -match "ip_addresses") {
            $start = $true
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用regex 从文件中提取所有 IP 地址。 regex 上的所有积分都转到 this answer

      下面会给你一个array,如果你需要他们用逗号分隔,-join ',' 会做。

      $file = Get-Content ./inputs.txt -Raw
      
      [regex]::Matches(
          $file,
          '\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
      ).Value
      

      注意:regex 将仅支持有效的 IPv4 地址,999.2.3.4 之类的地址将匹配。

      【讨论】:

        猜你喜欢
        • 2012-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 1970-01-01
        • 2020-09-16
        • 1970-01-01
        相关资源
        最近更新 更多