Powershell - 拆分数组值保留第一个元素

Powershell - 拆分数组值保留第一个元素

我正在尝试使用以下代码从过滤后的 JSON 中提取 IP:

$curl = Invoke-WebRequest -Method Get -Uri "http://urltojson.com/file.json"
$curl2 = $curl.Content.replace("Script", "Script_").replace("iphone", "iphone_").replace("android", "android_").replace("ipad","ipad_")  | ConvertFrom-Json
$curl3 = $curl2 | Where-Object {$_.Name -eq "/Common/cloudfront_nets"} | Select-Object -ExpandProperty data
$curl3
[System.Collections.ArrayList]$curl3[0] = $curl3
$curl3[1]

返回以下内容

13.59.250.0 255.255.255.192:区域:美国东部-2-服务:CLOUDFRONT

52.57.254.0 255.255.255.0:区域:eu-central-1-服务:CLOUDFRONT

54.182.0.0 255.255.0.0:区域:GLOBAL-服务:CLOUDFRONT

52.212.248.0 255.255.255.192:区域:eu-west-1-服务:CLOUDFRONT

205.251.250.0 255.255.254.0:区域:GLOBAL-服务:CLOUDFRONT

35.162.63.192 255.255.255.192:区域:美国西部-2-服务:CLOUDFRONT

13.32.0.0 255.254.0.0:区域:GLOBAL-服务:CLOUDFRONT

205.251.254.0 255.255.255.0:区域:GLOBAL-服务:CLOUDFRONT

我正在努力简单地输出 IP(没有子网掩码)

有人可以帮忙吗?

答案1

尝试:

$datas=@"
13.59.250.0 255.255.255.192 : region: us-east-2-service: CLOUDFRONT

52.57.254.0 255.255.255.0 : region: eu-central-1-service: CLOUDFRONT

54.182.0.0 255.255.0.0 : region: GLOBAL-service: CLOUDFRONT

52.212.248.0 255.255.255.192 : region: eu-west-1-service: CLOUDFRONT

205.251.250.0 255.255.254.0 : region: GLOBAL-service: CLOUDFRONT

35.162.63.192 255.255.255.192 : region: us-west-2-service: CLOUDFRONT

13.32.0.0 255.254.0.0 : region: GLOBAL-service: CLOUDFRONT

205.251.254.0 255.255.255.0 : region: GLOBAL-service: CLOUDFRONT
"@


# if you want put the result into an array
$ipv4s = @()


Write-Host ("In loop");
# if file provide from a linux system change `r`n` for `n
([String]$datas).split("`r`n") |% { 

    if($_){

        # adjust index for your choice (here ipv4 addr) at index 0
        [String]$ip     = ([String]$_).split(" ")[0];
        $ipv4s += $ip;

        Write-Host ($ip);
    }

}


Write-Host -ForegroundColor Yellow ("`r`nTotal IPV4s : " + $ipv4s.Count);
Write-Host ("In array");
$ipv4s | % { write-host $_}
# equivalent
#foreach($ipv4 in $ipv4s){
#    write-host $ipv4;
#}
# You can access to object with index (in range of $ipv4s.Count)
# Write-Host ($ipv4s[0]); Write-Host ($ipv4s[1]); etc...

出去

In loop
13.59.250.0
52.57.254.0
54.182.0.0
52.212.248.0
205.251.250.0
35.162.63.192
13.32.0.0
205.251.254.0

Total IPV4 : 8
In array
13.59.250.0
52.57.254.0
54.182.0.0
52.212.248.0
205.251.250.0
35.162.63.192
13.32.0.0
205.251.254.0

答案2

感谢@J-barnaby 给出的第一个正确答案,较短的位(假设$curl3[1]包含您需要格式化的输出数据)将如下所示:

# split the text into array of strings on line breaks and filter empty lines
$output = $curl3[1] -split "`r`n" | ? {$_} 

# process each line
$addresses = foreach ($line in $output)
{
    # further break each line into space delimited words, selecting first word
    $line.Split(' ')[0] 
}

# output the resulting list
$addresses

相关内容