PowerShell: Beginner pittfalls

powershell

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 = “john@contoso.com”.
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 john@contoso.com, 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”}

Datetime
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) {

$user.userprincipalname

}

System variables
Do not create new variables named the same as these predefined PowerShell variables:
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-5.1

 

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 )

Google+ photo

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

Connecting to %s