Tuesday, September 15, 2009

How can I parse a string of text in PowerShell?



For you vbscripters out we had a built in function call split that allowed us to split text strings into an array. We have the same functionality as method in PowerShell.

First create a variable:
  • $Var1="“10,15,20,9,8,7”"

Now let's discover the methods that are available to this variable. Powershell is smart enough to know that this variable is a string.
  • $Var1 | Get-Member





Noticed that Split is a method. Let’s go ahead and execute this method.
$Var1.Split(“,”).



The “,” tells PowersShell that our delimiter is going to be the comma. You can choose any character to be your delimiter.

You can also treat these as cells in an array.

• $Var2 = $Var1.Split(“,”)
• $Var2[1]

After you execute the second command, the contents of cell 1 in the array $Var2 will be displayed. In this case, it should be 15.

1 comment:

Anonymous said...

V2 also introduces the -split operator (get-help about_split,) and you can also go all the way with http://www.leeholmes.com/blog/parsetextObjectAWKWithAVengeance.aspx

Lee Holmes [MSFT]
Windows PowerShell Development
Microsoft Corporation