我需要从下面的输入中分离ip和主机名,并使用powershell转换为数组对象我有一个类似的输入
$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",""'
我的预期输出将低于
$existing_ips = "192.168.1.12","","192.168.1.15","192.168.1.16"
$existing_hosts = "node.example.com","node1.example.com","node2.example.com",""
上面的变量existing_ips和existing_hosts可能有空或null值,以及这些变量之间的等效值,我需要将其保存在一个单独的变量中
最终输出将低于
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' -> ''
虽然可能有更简洁的解决方案,但为了概念清晰,我会使用基于-split
和-replace
:的多步骤方法
$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",""'
# Extract the two sub-lists from the input string.
$ipList, $hostList =
$docu_results -split 'existing IPs:|existing hostname:' -ne ''
# Split each list into an array of its elements.
$existing_ips = $iplist.Trim() -split ',' -replace '"'
$existing_hosts = $hostList.Trim() -split ',' -replace '"'
注:
- 使用数组作为LHS,PowerShell比较运算符充当筛选器(请参阅此答案(,这意味着上面的
-ne ''
会从-split
操作输出的数组中筛选出任何空令牌;空(-string(标记是由于其中一个分隔符位于输入字符串的最开始