• vadim@workflowexcellence.com
  • Utah, United States

PowerShell Basics 101

Here’s a few basics that I’m aware of that make things easier for me when I play around with PowerShell.

Variables

PowerShell variables all start with a dollar ($) sign.
Initializing a variable requires simply giving it a name, followed by an equals (=) and the value

$myVar = 1

If you want to initialize a variable to multiple values, eg. an array of numbers, you simply comma delimit it

$myVar = 1,2,3

You can also set one variable to another

$myNewVar = $var

Displaying Variable Values
To display the value of a variable, just put in the dollar variable name.

$myVar

This will show the value of that variable.
If you variable is an array of values, and you want a specific value, then you use square brackets after the variable name, and insert an index in to the brackets.  NOTE: PowerShell is indexing starts at zero (0).  So the first index into your array is at position 0.

$myVar[1]

This will give you the second value in your variable array.  Since we initialized $myVar to 1,2,3 before, $myVar[1] will return the value 2.

Iterate through each value in an Array Variable

To go through each value in an array variable, you can use a foreach.  Similar to the For Each action in Nintex Workflow.

Using the example above, where we have an array variable ($myVar = 1,2,3).

foreach ($var in $myVar)
{
  $var
}

This will go through each value in $myVar and with each iteration, will store the value in a new temporary variable called $var.  Inside the ForEach, I’m simply displaying the value of $var.

If you are doing this in the SharePoint Management Shell, after the final }, press [enter] twice, and it will run the whole foreach you just typed in.

Leave a Reply

Your email address will not be published. Required fields are marked *