You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell将字符串拆分为IP和主机名两个数组对象

PowerShell 从指定输入拆分IP与主机名并配对校验的实现方案

1. 提取保留空值的数组变量

通过正则匹配提取原始字符串中所有双引号包裹的内容,空字符串也会正常保留,保证两个数组的位置一一对应:

# 定义原始输入变量
$docu_results = 'existing IPs: "192.168.1.12","","192.168.1.15","192.168.1.16"
existing hostname: "node.example.com","node1.example.com","node2.example.com",""'

# 提取IP数组
$ipLine = ($docu_results -split "`n") | Where-Object { $_ -match 'existing IPs:' }
$existing_ips = ($ipLine | Select-String -Pattern '"([^"]*)"' -AllMatches).Matches.Value | ForEach-Object { $_.Trim('"') }

# 提取主机名数组
$hostLine = ($docu_results -split "`n") | Where-Object { $_ -match 'existing hostname:' }
$existing_hosts = ($hostLine | Select-String -Pattern '"([^"]*)"' -AllMatches).Matches.Value | ForEach-Object { $_.Trim('"') }

执行后得到的$existing_ips和$existing_hosts完全符合要求,对应位置的空值会被保留。

2. 按位置配对输出并标记缺失数据

遍历两个数组相同索引的元素,正常配对的直接输出,存在缺失的记录下来最后统一展示:

$missingList = @()
# 取两个数组的最大长度作为遍历上限,兼容长度不一致的场景
$maxCount = [Math]::Max($existing_ips.Count, $existing_hosts.Count)

for ($index = 0; $index -lt $maxCount; $index++) {
    $currentIp = $existing_ips[$index] ?? ""
    $currentHost = $existing_hosts[$index] ?? ""

    if (-not [string]::IsNullOrEmpty($currentIp) -and -not [string]::IsNullOrEmpty($currentHost)) {
        Write-Host "$currentIp :: $currentHost"
    }
    elseif (-not [string]::IsNullOrEmpty($currentIp)) {
        Write-Host $currentIp
        $missingList += "value is missing for '$currentIp' -> ''"
    }
    elseif (-not [string]::IsNullOrEmpty($currentHost)) {
        $missingList += "value is missing for '' -> '$currentHost'"
    }
}

# 输出缺失数据提示
Write-Host "`nmissing data: "
$missingList | ForEach-Object { Write-Host " $_" }

输出效果示例

192.168.1.12 :: node.example.com
192.168.1.15
192.168.1.15 :: node2.example.com
192.168.1.16

missing data: 
 value is missing for '' -> 'node1.example.com'
 value is missing for '192.168.1.16' -> ''

注:需求示例中192.168.1..12属于笔误,实际输出为正常的IP格式。

内容的提问来源于stack exchange,提问作者Suganthan Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:06:06