Powershell - 从字符串中删除

时间:2017-07-13 18:53:57

标签: json windows powershell scripting

我使用以下语法从JSON文件中提取IP列表

$Request = 'https://url-to-json.com/file.json'
$AWSIPs = Invoke-WebRequest $Request | ConvertFrom-Json | Select-Object prefix -ExpandProperty prefixes -ExcludeProperty ("/.*") | Where-Object -Property "service" -EQ "service_name" | select ip_prefix
foreach ($awsip in $AWSIPs){
echo $awsip
}

以这种方式返回IP列表: - 0.0.0.0/00

  • 0.0.0.0/00
  • 0.0.0.0/00
  • 0.0.0.0/00
  • 0.0.0.0/00
  • 0.0.0.0/00

我需要使用这个IP列表,但是在我能够这样做之前我需要在结尾处删除/ 00(显然不是00但它是子网掩码,这很少相同)。

我非常感谢你的帮助。

感谢。

1 个答案:

答案 0 :(得分:5)

基于-replace的解决方案:

$ips =  '0.0.0.0/00',
        '0.0.0.1/01',
        '0.0.0.2/02',
        '0.0.0.3/03',
        '0.0.0.4/04'

$ips -replace '(.*)/.*', '$1'

请注意如何将数组直接用作-replace操作的LHS。

以上产量:

0.0.0.0
0.0.0.1
0.0.0.2
0.0.0.3
0.0.0.4

-split也是一个选项,但为了避免额外的复杂性,您需要一个显式循环:

foreach ($ip in $ips) {
  ($ip -split '/')[0]
}

可以避免显式循环,但由于性能和可读性的原因,这可能不值得做;但它确实显示了PowerShell的灵活性:

($ips -split '/')[(0..($ips.Count-1)).ForEach({ $_ * 2 })]