People that are new to PowerShell and perhaps have never had any hands-on with Microsoft .Net Framework programming may not be familiar with some of the very powerfull string processing capabilities available. I tend to use the string class' split function quite a lot in my code samples and thought it might be good to do a quick explanation of how it works to the uninitiated.
First, let's assign a string value with some sort of delimiters built in (such as commas).
PS C:\powershell> $myString = "element-a,element-b,element-c" |
To extract an element, we can use the split method to break the string apart into individual pieces using the comma as a delimiter.
PS C:\powershell> $myStringArray = $myString.split(",") |
$myStringArray now contains 3 items
We can demonstrate this by inspecting the length property and also by typing the name to display the contents
PS C:\powershell> $myStringArray.length 3 PS C:\powershell> $myStringArray element-a element-b element-c |
We can index directly into the array without reading it into a variable by appending a subscript component to the end of the split method
PS C:\powershell> $myString.split(",")[0] element-a PS C:\powershell> |
Note: .Net arrays are zero-based so the first index into an array would be [0], the second would be [1], and so on.