Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Go Up


Gartner complimentary report: Buyers’ Guide for Privileged Access Management
×

Netwrix Blog

Search

Security & Compliance

IT Operations

Information Governance

Game Zone

Cyber Chief Magazine

SysAdmin Magazine

eBooks

Best Practices

How-to guides

Webinars

Free tools

Subscribe

Contact us

Blog
PowerShell Variables and Arrays

Blog / IT Operations / 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.

Handpicked related content:

Free Download: PowerShell Scripting Tutorial

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

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] Text string $var1 = "Netwrix"


System.String

[char] Symbol [char]$var1 =


System.Char 0x265b

[bool] Boolean (value can be $true or $false) $var1 = $true


System.Boolean

[int] 32-bit integer $var2 =


System.Int32 235235345

[long] 64-bit integer $var2 =


System.Int64 2352353457

[decimal] 128-bit decimal number with the letter “d” at $var2 =


System.Decimal the end 23523.53456d

[double] 8-byte decimal floating point number [double]$var2 =


S t D bl 23523 53456
System.Double 23523.53456
Variable Type Description Example
[single] 32-bit floating point number [single]$var2 =
System.Single 23523.53

[DateTime] Date and time $var3 = get-date


System.DateTime

[array] Array (discussed in detail later in this article) $var3 = "first",


System.Object[] "second", "third"

[hashtable] Hash table $var3 =


System.Collections.Hashtable The difference between hash tables and @{1="one";
arrays is that indexes are used in arrays, and 2="two";
named keys are used in hash tables. Hash 3="three"}
tables are built using the following format: @
{key = "value"}
To add an item to a hash table, you can $var3.Add("4",
either assign it a key that does not already "four")
exist or use the Add () method. If the $var3.5 = "five"
assignment is made to an existing key, the $var3.Remove("2")
value of the key changes to the assigned
one. To remove an item from a hash table,
use the Remove () method.

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()

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()

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_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")

$a ay8 @( a t , e cu y , e us , Jup te , Satu , a s , eptu e , uto )


 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.

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

MORE GREAT READING

Running LAPS in the Race to Security

Kevin Joyce October 25, 2021


Managing SharePoint Online using PowerShell

Jeff Melnick June 4, 2021

Most Useful SharePoint PowerShell Commands

Jeff Melnick January 17, 2019

Using PowerShell to Create ZIP Archives and Unzip Files

Russell Smith June 4, 2021


FEATURED TAGS

Active Directory CISSP Cyber attack Data classification

Data governance Data security GDPR Insider threat

IT compliance IT security Office 365

Privileged account management Risk assessment SharePoint

Windows Server ...


FEATURED TAGS

Active Directory CISSP Cyber attack Data classification Data governance

Data security GDPR Insider threat IT compliance IT security

Office 365 Privileged account management Risk assessment SharePoint

Windows Server ...


About Us
About Netwrix
About Netwrix Blog
Write for Us
Privacy
Featured Topics
Cyber Security
Compliance
Free Tools
PowerShell
Free Resources
Top 7 Free Netwrix Tools
Best Practices
How-tos
Webinars
eBooks
SysAdmin Magazine
Cyber Chief Magazine
Network Security
Active Directory
Group Policy
Exchange
Windows Server
Network Devices
VMware
Azure AD
Data Security
Windows File Servers
EMC
NetApp
SharePoint
SQL Server
Oracle Database
Office 365
Compliance
PCI DSS
HIPAA
SOX
FISMA
GLBA
GDPR
ISO 27001
© 2021 Netwrix Corporation. All rights reserved.

You might also like