/* ]]> */
Nov 202009
 

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).

?View Code POWERSHELL
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.

?View Code POWERSHELL
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

?View Code POWERSHELL
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

?View Code POWERSHELL
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.

 Posted by at 2:02 pm

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Page optimized by WP Minify WordPress Plugin