Home > Software engineering >  How to split string variables into two array object variables using powershell?
How to split string variables into two array object variables using powershell?

Time:11-05

I need to split ips and hostnames from the below the input and convert into array object using powershell I have a input like below

$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",""'

my expected output would be like below

$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",""

The above variables existing_ips an d existing_hosts might have empty or null value and its equivalent values in between these variables and i need to save that in a separate variables

Final output would be like below

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' -> ''

CodePudding user response:

While there may be more concise solutions, for conceptual clarity I'd use a multi-step approach based on -split and -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 '"'

Note:

  • With an array as the LHS, PowerShell comparison operators act as filters (see this answer), which means that -ne '' above filters out any empty tokens from the array that the -split operation outputs; an empty(-string) token results from the fact that one of the separators is at the very start of the input string.
  • Related