PowerShell: Beginner pittfalls


As i have started to advance my PowerShell skills, il share what common error i came upon in the beginning. Not knowing some of these can create some confusion and frustration.
Please comment below any other tips you have for other beginners.

Variable scope.
If you write a script that contains a function, and you use that function, but the variable is blank when using that variable later in the script.
The scope for the variable is only inside of the function. To define a variable named $servers in the whole script, you do it like this: $script:servers

Clear out variables.
When debugging or testing a script over and over again, and you run into problems you cant quite explain: Open a new PowerShell session/window, so you are shure all variables are cleared out.

When comparing variables, make shure they are the same.
If you for example define a variable as $upnA = “[email protected]”.
Then you deine another like this: $upnB = Get-ADuser John | Select-Object userprincipalname.
If you after defining the variables do the following If statement:
If ($upnA -eq $upnB) {“The variables are the same”}
This will come out as not true. If you look at the output of $upnB, you see that even though the only UPN in the variable is [email protected], it also contains the header of that type of value.
To make the If statement true, you have to do it like this:
If ($upnA -eq $upnB.userprincipalname) {“The variables are the same”}

Make shure what date format the scripts are using. mm/dd/yyyy, dd/mm/yyyy etc…

Logic statements
Logic statements can make you crazy. Make shure to test them before using them in a script.
For example:

$A = “1”
$B = “2”
if ($A -eq “1”){
“Value equals $1”
Else {“Value equals $B}

Writing to variable in a foreach loop
If you have a Foreach loop and need to write each loop to a variable, you need to add it to a array variable like this:

$usernames = @()
foreach ($user in $users) {

$usernames += $user.userprincipalname


or define the variable like this:

$usernames = foreach ($user in $users) {



System variables
Do not create new variables named the same as these predefined PowerShell variables:


I hope someone finds this usefull.

One thought on “PowerShell: Beginner pittfalls

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s