Archive

Archive for April, 2020

PowerShell – Quick way to iterate through a list of items (Part II)

30th April, 2020 Leave a comment

I previously wrote an article about iterating though a list of items in Powershell. Sometimes you get an output from another application (such as a list of usernames) and just want to quickly get some additional information (such as the displayName of the user from Active Directory).

My previous post worked to a limited extent, but I sometimes had issues with it. It turned out that each item may have an extra character at the end of the string. After a bit of investigation appears to be a CR. Not a problem, I just modified the split to include that as well:

$guids = $data.split("`r`n")

Unfortunately, this doubled the number of items returned with every other one being blank. After a bit of investigation I found this forum post with an excellent explanation: https://powershell.org/forums/topic/string-split-on-crlf-produces-extra-member/

To summarise, the System.String Split method will take an array of characters and split on each occurrence of any character in the array, rather than split on the complete string.

The solution is to use the regex -split operator instead. This also gives an additional benefit of allowing splits on several characters or groups of characters, so we can include all combinations of CR LF.

I’ve also updated the example to use a here-string (@’ ‘@) which allows pasting the data into a continuous block without having to modify the first or last items in the list. Here’s the updated example:


$data = @'
65c43d1cb95b8646a0a8d1342d0e9326
946018fb0b250146a7625cc743d47377
72163af67ac45146836c62b7760aee28
e6fe3309096e024fa6a8809093c19cf3
097fcd70c2cebd43b67cc237ec0b1d43
b196d288b2fcc14ca0422e2eeb14410b
'@

$guids = $data -split "`r`n|`r|`n"

foreach ($guid in $guids) {
$guid
}

Categories: PowerShell, Programming