PowerShell String to Array to a Foreach Loop

I always forget to use the Split command (or write it in VBScript before I remember PowerShell). The following command takes a comma separated list (string), and splits the string into an array. Then loop through the array in a foreach loop:

$list = “1,2,3,4”;
$lists = $list.split(“,”);
foreach($l in $lists){ $l }

That’s easy enough to remember. To access any item from the list, you can simply print: $lists[0]

Leave a Reply