In the previous article, named PowerShell Scripting Tutorial for Beginners, we explored how to use the PowerShell console to execute scripts and learned what cmdlets are, how to get their properties and how to use pipes to pass data from one cmdlet to another.
In this article, we will move on to variables and arrays, including what they are and how we can create, remove and change them.
PowerShell Variables
A variable is a unit of memory in which values are stored. A variable in PowerShell begins with “$” (dollar sign) and its name can contain any letters, numbers and underscores. To assign a value to a variable, we use the “=” operator. To display the value of a variable, simply enter the variable. The following commands assign a value to a variable and then verify it:
$var1 = 777 $var1
You can perform arithmetic operations over numbers:
$var1 = 777 $var2 = 333 $var3 = $var1 + $var2 $var3
You can also combine strings using the “+” operator:
$var1 = "Complete" $var2 = "Visibility" $var3 = $var1 + $var2 $var3
If you add a number to a string, the number automatically becomes a string:
$var1 = "Netwrix" $var2 = 2018 $var3 = $var1 + $var2 $var3
Variable Types
The PowerShell variable type is set automatically based on the value you assign to it, but you can also assign the type manually:
[string]$var1 = "Netwrix"
To find out what type a variable is, we use the “GetType ()” parameter:
$var1 = "Netwrix" $var1.GetType().FullName
As we can see, our $var1 variable has the “System.String” type.
Here are descriptions of all the PowerShell variable types:
Variable Type | Description | Example |
---|---|---|
[string] System.String |
Text string | $var1 = "Netwrix" |
[char] System.Char |
Symbol | [char]$var1 = 0x265b |
[bool] System.Boolean |
Boolean (value can be $true or $false) | $var1 = $true |
[int] System.Int32 |
32-bit integer | $var2 = 235235345 |
[long] System.Int64 |
64-bit integer | $var2 = 2352353457 |
[decimal] System.Decimal |
128-bit decimal number with the letter “d” at the end | $var2 = 23523.53456d |
[double] System.Double |
8-byte decimal floating point number | [double]$var2 = 23523.53456 |
[single] System.Single |
32-bit floating point number | [single]$var2 = 23523.53 |
[DateTime] System.DateTime |
Date and time | $var3 = get-date |
[array] System.Object[] |
Array (discussed in detail later in this article) | $var3 = "first", "second", "third" |
[hashtable] System.Collections.Hashtable |
Hash table The difference between hash tables and arrays is that indexes are used in arrays, and named keys are used in hash tables. Hash tables are built using the following format: @ {key = "value"} To add an item to a hash table, you can either assign it a key that does not already exist or use the Add () method. If the assignment is made to an existing key, the value of the key changes to the assigned one. To remove an item from a hash table, use the Remove () method. |
$var3 = @{1="one"; 2="two"; 3="three"} $var3.Add("4", "four") $var3.5 = "five" $var3.Remove("2") |
You probably already understood that you can write to the variable not only some definite value and noticed the class System.Object [] in the table. To this variable you can write the output of any cmdlet.
Variable Scope
The variable scope in PowerShell can be either local or global. By default, a variable has a local scope. A variable is bounded by its current scope; for example, a local variable can be available in a current function or script, while a global variable is active throughout the current PowerShell session. To denote a global variable, use the format $Global: variable = value, as illustrated in the following command:
$Global:var4 = 12
PowerShell Variable Examples
List variables
To list all current available variables, run the ls variable:* command. Here is an example of the output:
Set variable
You can create a variable by simply assigning it a value. For example, the command $var4 = “variableexample” creates a variable named $var4 and assigns it a string value. The double quotes (” “) indicate that a string value is being assigned to the variable.
Get variable
This is very similar to the list variable command, just using another cmdlet:
Get-Variable | Out-String
Print variable
You can output a variable a .txt, .csv or HTML file.
To write to a .txt file, use the Out-File command:
$var5 = "Hello World!" $var5 | Out-File C:\scripts\Hello_World.txt
To export data to a .csv file, use the Export-Csv command:
$var6 = Get-Process $var6 | SELECT Name, Path | Export-Csv -Path C:\scripts\processes.csv
And to write to an HTML file, use the ConvertTo-Html command:
$var6 = Get-Process $var6 | ConvertTo-Html -Property Name, Path > C:\scripts\processes.html
To read a file that we exported, we use the Get-Content cmdlet:
Get-Content C:\scripts\processes.csv
Clear variable
To clear the contents of a variable, use the Clear-Variable cmdlet:
Clear-Variable -name var6 #without $
Remove variable
To completely remove a variable, use the Remove-Variable cmdlet:
Remove-Variable -name var6 #without $
PowerShell Arrays
An array is a type of a variable. It is a set of components (array elements) arranged in a certain order. Elements of the array are numbered sequentially, and you access an element using its index number.
When creating arrays, be aware of the default PowerShell behavior. If you create an array with multiple elements, PowerShell will create an array, as you intend. For example, put a few numbers into an array and then check the data type of the variable:
$array1 = 1, 2, 3 $array1.GetType()
As you can see, in this case, PowerShell created an array (System.Array).
However, if you put just one value in a variable, then PowerShell will not create an array:
$array1 = 1 $array1.GetType()
Of course, you cannot always tell in advance how many objects will be received as a result of executing a particular command, so you need to have code that will always treat the result as an array.
You can do this in many ways. For example, you can use the “,” operator. If a comma is used as a binary operator, then a normal array is created; if it is used as a unary operator, the array has just one element. For example, here is how we can get an array consisting of one element:
$array1 = ,1 $array1.GetType()
Alternatively, you can explicitly specify the data type for a variable:
[object[]]$array1 = 1 $array1.GetType()
Finally, you can also create an array using subexpression operator “@“, which forms an array even if no objects at all are specified. It is very convenient to initialize a variable as an array, and then add objects to it without worrying about their number.
$array3 = @() $array3.GetType()
Note that each element of an array has its own data type, and the type object[] allows you to add any values to the array. If necessary, you can restrict the members of the array to a specific data type — then you’re creating a “typed array”. For example, you can specify that array elements must be integer values:
[int32[]]$array1 = 1 $array1.GetType()
And so we define system processes as array members:
[System.Diagnostics.Process[]]$array1 = Get-Process $array1.GetType()
Array List
If you will modify or search an array frequently, you can use the ArrayList class, which is designed to let you easily add, remove, and search for items in it:
$array3 = New-Object System.Collections.ArrayList
Array Index
An index in the array is a value, typically a numeric integer used to identify and reference an array element. Array indexes start at either zero or one, depending on the programming language. Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].
$var3 = "first", "second", "third"
Multidimensional Arrays
Multidimensional arrays are variables that can be used to store information in a table without having to write it to a real database. It looks like a hash table, but it can store different types of information, such as strings and integers. In fact, you can imagine a multidimensional array as a table with columns and rows, where each cell has its own index inside a PowerShell environment.
$mdarray1 = @() $mdarray1_counter ++ $mdarray1 += ,@($mdarray1_counter, 'Earth',12742) $mdarray1_counter ++ $mdarray1 += ,@($mdarray1_counter, 'Mars',6779) $mdarray1_counterr ++ $mdarray1 += ,@($mdarray1_counter, 'Venus',12104) $mdarray1_counter ++ $mdarray1 += ,@($mdarray1_counter, 'Saturn',116464) foreach($array10 in $mdarray1) { Write-host ($array10) }
PowerShell Array Examples
Sort array
If an array contains only one data type, you can sort the values using the Sort method:
$array3 | Sort
To sort an array with more than one data type, you need to use the Sort-Object cmdlet.
Add to array
First, let’s create an array:
$array5 = "one", "two", "three", "four", "five" $array5.gettype()
To easily modify our array, we need to add it to the arraylist collection:
[System.Collections.ArrayList]$ArrayList1 = $array5 $ArrayList1.GetType()
As you can see, the BaseType has changed and we can easily modify our array now:
$ArrayList1.Add("six") $ArrayList1.Remove("three") $ArrayList1
Array length
To return the number of elements in array, use the .length parameter:
$array6 = 1,2,3,4,5,6 echo $array6.Length
Remove item from array
To remove an item, use the .Remove command. Again, it is better to use an arraylist:
[System.Collections.ArrayList]$ArrayList1 = $array5 $ArrayList1.GetType() $ArrayList1.Remove("three") $ArrayList1
Array contains
If you want to see if any of the elements in an array contains a particular value, use the Contains method:
$array7 = 1,2,5,8,3,4,5 $array7.Contains(2) $array7.Contains(12)
Clear array
Even though most of the array operations in PowerShell are relatively easy to accomplish, there is no simply way to delete an array. The easiest way to get rid of an entire array is to assign the variable $null to it:
$array7 = $null $array7
To check if our array is null, run the following script:
$array7 -eq $null
In PowerShell, if a variable is null, you can’t apply any methods to it.
Print array
To print a whole array, we can use the same methods described for printing variables.
To write to a .txt file, use the Out-File command:
$var5 | Out-File C:\scripts\array.txt
To export to a .csv file, use the Export-Csv command:
$var6 | Export-Csv -Path C:\scripts\array.csv
And to write to an HTML file, use the ConvertTo-Html command:
$var6 | ConvertTo-Html > C:\scripts\processes.html
Loop through an array
In order to handle each element in an array one after another, we need to make a loop using the foreach operator. For example if we declare a string array and want to count the length of each word in the array, we should run the following script:
$array8 = @("Earth","Mercury","Venus","Jupiter","Saturn","Mars", "Neptune", "Pluto") foreach ($array in $array8) { "$array = " + $array.length }
In this article, we learned about variables and their types. Then we explored one variable type — the array— in detail and learned how to play with it. With this information, you are ready to dive into PowerShell even deeper.