Professional Documents
Culture Documents
PowerShell Variables and Arrays
PowerShell Variables and Arrays
Gartner complimentary report: Buyers’ Guide for Privileged Access Management
×
Netwrix Blog
Search
IT Operations
Information Governance
Game Zone
SysAdmin Magazine
eBooks
Best Practices
How-to guides
Webinars
Free tools
Subscribe
Contact us
Blog
PowerShell Variables and Arrays
Jeff Melnick
Published: October 4, 2018
Updated: May 18, 2021
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
Variable Types
Variable Scope
PowerShell Variable Examples
List variables
Set variable
Get variable
Print variable
Clear variable
Remove variable
PowerShell Arrays
Array List
Array Index
Multidimensional Arrays
PowerShell Array Examples
Sort array
Add to array
Array length
Remove item from array
Array contains
Clear array
Print array
Loop through an array
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
$var2 = 333
$var3
$var1 = "Complete"
$var2 = "Visibility"
$var3
$var1 = "Netwrix"
$var2 = 2018
$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
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.
$var6 = Get-Process
$var6 = Get-Process
Get-Content C:\scripts\processes.csv
Clear variable
To clear the contents of a variable, use the Clear-Variable cmdlet:
Remove variable
To completely remove a variable, use the Remove-Variable cmdlet:
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()
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()
Fi ll l t i b i t “@“ hi h f
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()
[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:
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].
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_counter ++
$mdarray1_counterr ++
$mdarray1 counter ++
$mdarray1_counter ++
foreach($array10 in $mdarray1)
Write-host ($array10)
$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.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:
Print array
To print a whole array, we can use the same methods described for printing variables.
}
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.
Jeff Melnick
Jeff is a former Director of Global Solutions Engineering at Netwrix. He is a long-time
Netwrix blogger, speaker, and presenter. In the Netwrix blog, Jeff shares lifehacks, tips
and tricks that can dramatically improve your system administration experience.
PowerShell
Show Comments