【问题标题】:How to split string variables into two array object variables using powershell?如何使用powershell将字符串变量拆分为两个数组对象变量?
【发布时间】:2021-12-18 23:23:17
【问题描述】:

我需要从输入下方拆分 ips 和主机名,并使用 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 和d 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' -> ''

【问题讨论】:

    标签: arrays powershell


    【解决方案1】:

    虽然可能有更简洁的解决方案,但为了概念清晰,我会使用基于 -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 '"'
    

    注意:

    • 使用 array 作为 LHS,PowerShell 比较运算符充当 过滤器(请参阅 this answer),这意味着上面的 -ne '' 会过滤掉来自-split 操作输出的数组;一个空(-string)标记是由于其中一个分隔符位于输入字符串的开头。

    【讨论】:

    • 非常感谢@mklement0.. 你节省了我的时间?
    • 很高兴听到它有帮助,@SuganthanRaj;我的荣幸。
    猜你喜欢
    • 2013-12-28
    • 1970-01-01
    • 2021-12-11
    • 2020-12-27
    • 1970-01-01
    • 2022-01-05
    • 2020-04-11
    • 1970-01-01
    • 2015-11-30
    相关资源
    最近更新 更多