PS
Powershell Tutorial Online

Variables



First PS1 file

A PowerShell script is really nothing more than a simple text file.
The file contains a series of PowerShell commands, with each command appearing on a separate line.
For the text file to be treated as a PowerShell script, its filename needs to use the .PS1 extension.

  • Step 1 :- Create a simple text file.
  • Step 2 :- Write any powershell commands
    E.g. Get-Process | Sort-Object ID
    Note : Get-Process using this you can get a list of processes by using the Get-Process cmdlet, "Sort-Object ID" for the list will be sorted by ID. Use pipe symbol for seperation "|"
  • Step 3 :- Rename extension .txt to .PS1 extension (Create at some location with FirstPowershell.PS1 e.g. C:\PowershellScripts\)
  • Step 4 :- Open powershell and Run C:\PowershellScripts\FirstPowershell.PS1

Powershell Variables
If you want to use the variable, simply call it by name and prefix with '$' symbol.
$firstVarible = "This is a test" (Assign text to varible)
$firstVarible (Print varible value output should be "This is a test")
$firstVarible = $firstVarible + " Added text"
$firstVarible (Print varible value output should be "This is a test Added text")

Variables

Built in variables in PowerShell.

[string] Fixed-length string of Unicode characters
[char] A Unicode 16-bit character
[byte] An 8-bit unsigned character
[bool] Boolean True/False value
[int] 32-bit signed integer
[single] Single-precision 32-bit floating point number
[double] Double-precision 64-bit floating point number
[long] 64-bit signed integer
[DateTime] Date and Time
[decimal] A 128-bit decimal value
[array] An array of values
[hashtable] Hashtable object
[xml] Xml object

Variables - allows us to store single bits of information.

Launch PowerShell and let’s get started…

PowerShell Variables

Think of a variable as an imaginary box where we store information. Two basic uses of variables are:

  • Store information that will be later utilized within a script.
  • Store information that is a result of running a script.

In PowerShell, variables can contain text strings, integers, and even objects (complete with properties and methods). Special variables exist, which are pre-defined within PowerShell. We have worked with one of these variables ($_) in a prior tutorial.

Special Variable Examples

  • $_ – Contains the current pipeline object, used in script blocks, filters, and the where statement.
  • $Args – Contains an array of the parameters passed to a function.
  • $Error – Contains objects for which an error occurred while being processed in a cmdlet.
  • $Home – Specifies the user’s home directory.
  • $PsHome – The directory where the Windows PowerShell is installed.

To view the complete list of Special Variables in PowerShell, type the following:

Get-Help about_automatic_variables<enter>

In VBScript, we have to declare variables before using them. For example:

dim strComputer
dim strUser
dim intDate
strComputer = “MyComputer”
etc…

In PowerShell, ALL variable names must start with the “$” character. Once data is assigned to a PowerShell variable, it’s automatically declared. The “=” operator is used to assign data to a variable. Here is a simple example of creating a variable in PowerShell:

$strComputer = “Computer1″<enter>

There is a “Set-Variable” cmdlet that can also be used:

Set-Variable -Name strUser -Value “John Doe”<enter>

You can use virtually any variable name you choose, names are not case sensitive. Note: there are illegal characters such as; ! @ # % & , . and spaces. PowerShell will throw an error if you use an illegal character.

I stated virtually any name as PowerShell does have a set of keywords that are reserved and cannot be used as variable names:

  • break
  • continue
  • do
  • else
  • elseif
  • filter
  • foreach
  • function
  • if
  • in
  • return
  • switch
  • until
  • where
  • while

When naming variables, I continue to use the caMel case naming convention I became accustomed to in VBScript. The first part of the name (str) reminds me that the variable I’m working with contains “text string” data. If I were working with numbers, it might look like something this “$intMegaBytes.” Again, you can use any naming convention you wish.

Let’s verify that the $strComputer variable is holding the data we assigned to it.

Write-Output $strComputer<enter>

-or just type-

$strComputer<enter>
PowerShell Tutorial - strComputer

$strComputer Variable

image 7.0

The output verifies the data in the $strComputer variable is the “Computer1″ text string. Go ahead and verify the data value for the “strUser” variable.

$strUser<enter>

Did you get John Doe for the output? Yes… great! No?… I knew you were going to skip the long version of using the “Set-Variable” cmdlet.

Note: If you use the “Set-Variable” cmdlet and specify the -Name parameter, you do not use the “$” character when defining variables. Most of the time I use ($strComputer = “computerName”) to create variables. Just be conscious of this rule when using the “Set-Variable” cmdlet.

Working with Strings

A [sting] is a “text string” data type. There are many data types that we will be working with in PowerShell:

Type Description
[int] 32-bit signed integer
[long] 64-bit signed integer
[string] Fixed-length string of Unicode characters
[char] A Unicode 16-bit character
[byte] An 8-bit unsigned character
[bool] Boolean True/False value
[decimal] An 128-bit decimal value
[single] Single-precision 32-bit floating point number
[double] Double-precision 64-bit floating point number
[xml] Xml object
[array] An array of values
[hashtable] Hashtable object

Yep, we will be discussing them all at some point…

String Concatenation

Concatenation is the process of joining together two strings. Here is an example:

$strA = “Hello “<enter>
$strB = “World!”<enter>
$strC = $strA += $strB<enter>
$strC<enter>

We used += to join together variables $strA and $strB and store the new “text string” in variable $strC. The output from $strC is Hello World!

Most of the time you will see two strings joined together by using just the “+” operator. Like so; $strC = $strA + $StrB. Both result in the same output.

Aside from joining strings we can also replace words using the -replace parameter.

$strA = “Go east young man!”<enter>
$strB = $strA -replace “east”, “west”<enter>
$strB<enter>

Go west young man!

What the heck is Interpolation?

Quotes are used when working with string data, either double-quotes(” “) or single-quotes(‘ ‘). What’s the difference? Glad you asked… It’s called Interpolation. As stated at the beginning of this PowerShell training session, variables are stored for later use. Interpolation occurs when a string variable is enclosed in double-quotes and does not occur when single-quoted. Let me give you an example of what this means:

$strA = “fast”<enter>
Write-Host “Tom drives a $strA car.”<enter>

By double-quoting, the output of the “Write-Host” cmdlet is – Tom drives a fast car. This is interpolation, PowerShell substitutes the value of variable $strA. Let’s see what happens when using single-quotes:

$strA = “fast”<enter>
Write-Host ‘Tom drives a $strA car.’<enter>

Output – Tom drives a $strA car.
PowerShell does not substitute the variable.

Working with Numbers

PowerShell works with a number of data types, for example integers(9) and decimals (9.9). The PowerShell engine can automatically recognize the data type assigned to a variable. For example, it knows that $x = 1 is an integer data type. It also knows that $x = “Hello World!” is a string data type.

Assigning integer and decimal values are simple:

$x = 1<enter>
$y = 1.2<enter>
$x<enter>
$y<enter>

There are those rare occasions when PowerShell may have not assigned the proper data type to a variable, causing havoc with your script. Though it is not required, it is considered good form to assign the data type of a variable. Refer to the data type table presented earlier in the tutorial. Here are some examples:

[string]$strComputer = “MyFileServer01″<enter>
[int]$x = 9<enter>
[decimal]$y = 9.9<enter>

PowerShell Operators

  • = Assigns a value to a variable.
  • + or += Addition.
  • - or -= Subtraction.
  • * or *= Multiplication.
  • / or /= Division.
  • % or %= Modulus (retrieves the remainder of a division operation).

PowerShell follows the rules of math. Equations are read from left-to-right, multiplication and division are preformed then addition and subtraction.

$x = 10 * 2 / 5 * 2 + 5 * 5<enter>
$x<enter>

What answer did you get? Hopefully 33.

What about:

$x = 10 * 2 / 5 * (2 + 5) * 5<enter>
$x<enter>

Parenthesis can be used to alter the order of the mathematical rule. O.k. enough math class.

Note: PowerShell has two additional operators that you will use frequently. Make a mental note of these operators as you will be using them often in your script writing.

  • “++” Increments a value by 1.
  • “–” Decrements a value by 1. -Hard to see, it is minus minus or (- -) without the space.

Examples:

$x = 1<enter>
$x<enter>
1
$x++<enter>
$x<enter>
2
$x++<enter>
$x<enter>
3
$x–<enter>
$x<enter>
2

We will work with more data types when the advanced PowerShell tutorials are launched.
Here are nine exercises to complete. See if you can get through them all without looking at the answers. Answers provided below the exercise:

  1. Create a variable named $strComputer and assign the files server name FSrv01.
  2. Create a variable named $x and assign the number 7.
  3. Create a variable named $y, assign the data type and number 11.
  4. Create a variable named $Pi, assign the data type and number 3.14
  5. Concatenate the following variables, strA = “This is a ” and strB = “text string.”
  6. Using two variables, subtract 5 from 9.
  7. Using two variables, add 5 and 9.
  8. Assign the number 1 to variable $x and increment by 1.
  9. Get the answer for the following equation. 5 * 2 / 10 + 7 / 3 * 2.

Answers:

  1. $strComputer = “FSrv01″
  2. $x = 7
  3. [int]$y = 11
  4. [decimal]$Pi = 3.14
  5. strA + strB -or- strA += strB
  6. $x = 9<enter> $y = 5<enter> $x – $y<enter>
  7. $y + $x<enter>
  8. $x = 1<enter> $x++<enter> $x<enter>
  9. $x = 5 * 2 / 10 + 7 / 3 * 2<enter> $x = 6