When you store data in a variable, PowerShell can store it how you want it to be if you use the correct data type. This blog post will show you how that works and which data types I mostly use for my scripts.

Arrays are a fundamental data structure in most scripting and programming languages because they enable you to store, retrieve and manipulate a collection of items of various data types. Understanding arrays will enhance your ability to automate tasks using PowerShell.
An array is a data structure that can hold more than one value at a time. Think of it as a collection or a list of items of the same or different data types. Arrays are used in many scripting and programming languages, including Windows PowerShell.
Let’s delve into how to create and use an array in PowerShell.
Note: This post isn’t a solution, but provides some background information.
$doc.CustomDocumentProperties isn’t $null (i.e. the absence of an object reference) in a .NET sense: it still references an object, albeit a runtime-callable wrapper (RCW) for a COM object that represents a null value there, i.e. the absence of a COM object / class instance.
You can verify this by using the intrinsic pstypenames property to report the (inheritance chain of) type name(s) of a given instance:
$doc.CustomDocumentProperties.pstypenamesSystem.__ComObject#{00000000-0000-0000-0000-000000000000}
System.__ComObject
System.MarshalByRefObject
System.ObjectContrast this with trying to call a method on a true .NET $null value:
$null.Foo()InvalidOperation: You cannot call a method on a null-valued expression.Now as for why $doc.CustomDocumentProperties doesn’t point to an actual object and how to remedy that, I don’t know – if anybody knows, do tell us.
While working with PowerShell, you might need to check if a variable is an array in PowerShell. In this PowerShell tutorial, I will explain how to check if a variable is an array in PowerShell.
Now, let us check if a variable is an array in PowerShell using various methods.
Using the -is Operator
The most straightforward method to check if a variable is an array in PowerShell is by using the -is operator. This operator allows you to test if a variable is a certain data type. Here’s a simple example:
$a = 1,2,3,4,5
$a -is [array]If $a is an array, the output of the second line will be True. Conversely, if $a is not an array, it will return False.
You can check the output in the screenshot below:

Utilizing the .GetType() Method
Another way to determine if a variable is an array is by using the .GetType() method and checking its Name property. Here’s how you can do it:
$a = 1,2,3,4,5
$type = $a.GetType()
$type.Name -eq 'Object[]'Checking the Count Property
Arrays in PowerShell have a Count property that returns the number of elements in the array. You can use this property to check if a variable is an array or not. However, this method is not foolproof because single-item variables can be coerced into arrays and may also have a Count property. Here’s an example:
$a = 1,2,3,4,5
$a.CountThe $a.Count will return the number of elements in the array $a. If $a is not an array, PowerShell will attempt to convert $a to an array and then return the count. This means that even single-item variables will return a count of 1.
Using Custom Functions
You can write a custom function to check for an array for a more robust solution. This function can use a combination of the abovementioned methods to ensure accurate detection. Here’s a sample function:
function Test-IsArray($variable) { return $variable -is [array] -or ($variable.GetType().Name -eq 'Object[]')
}
$a = 1,2,3,4,5
Test-IsArray $aThis function, Test-IsArray, will return True if $a is an array and False otherwise.
Conclusion
If you want to identify whether a variable is an array in PowerShell, then you can use various methods. By using the -is operator, the .GetType() method, checking the Count property, or writing custom functions, you can accurately determine the data type of your variables.
Remember that while the Count property can be a quick way to check for an array, it’s not always reliable for single-item variables. The -is operator and .GetType() method are more accurate for identifying arrays. Custom functions offer flexibility and can combine multiple checks for a more thorough verification.
In this PowerShell tutorial, I have explained how to Check if a Variable is an Array in PowerShell using various methods.
You may also like:
If you are starting PowerShell and want to become an expert in it, you should have a complete understanding of PowerShell data types. In this PowerShell tutorial, I will show you various data types in PowerShell, including integers, floats, doubles, decimals, characters, strings, Booleans, dates, arrays, hash tables, and custom objects.
I will also show you how to check the data type in PowerShell.
Various Data Types in PowerShell
Here are a few data types in PowerShell with examples.
1. Integer
Syntax
[int]$integerVariable = 10Examples
Here is a complete example.
[int]$positiveInteger = 42
[int]$negativeInteger = -42
# Arithmetic operations
$sum = $positiveInteger + $negativeInteger
Write-Output $sumYou can see the output in the screenshot below:

2. Float and Double
Syntax
Here is the syntax for float and double data types in PowerShell.
[float]$floatVariable = 10.5
[double]$doubleVariable = 10.5Examples
Here is an example.
[float]$floatNumber = 3.14
[double]$doubleNumber = 3.141592653589793
# Arithmetic operations
$floatSum = $floatNumber + 2.86
$doubleSum = $doubleNumber + 2.86
Write-Output $floatSum # Output: 6.00000010490417
Write-Output $doubleSum # Output: 6.001592653589793When I executed the script using VS code and the output, you can see the output in the screenshot below:

3. Decimal
Syntax
Here is the syntax for decimal data types in PowerShell.
[decimal]$decimalVariable = 10.5Examples
Here is an example.
[decimal]$decimalNumber = 123.4567890123456789012345678
# Arithmetic operations
$decimalSum = $decimalNumber + 0.5432109876543210987654321
Write-Output $decimalSum Read How to Handle Errors with Try-Catch in PowerShell?
4. Character
Syntax
Here is the syntax of character data type in PowerShell.
[char]$charVariable = 'A'Examples
[char]$charA = 'A'
[char]$charB = 'B'
# Concatenation
$charConcat = "$charA$charB"
Write-Output $charConcatYou can see the output in the screenshot below:

5. String
Syntax
Here is the syntax:
[string]$stringVariable = "Hello, World!"Examples
Here is an example.
[string]$greeting = "Hello"
[string]$name = "World"
# String concatenation
$fullGreeting = "$greeting, $name!"
Write-Output $fullGreeting # Output: Hello, World!
# String length
$stringLength = $fullGreeting.Length
Write-Output $stringLength # Output: 136. Booleans
Syntax
Here is the syntax for booleans of data types in PowerShell.
[bool]$booleanVariable = $trueExamples
Here is a simple example of how to use boolean data types in PowerShell.
[bool]$isTrue = $true
[bool]$isFalse = $false
# Conditional check
if ($isTrue) { Write-Output "This is true."
} else { Write-Output "This is false."
}I executed the above PowerShell script, and you can see the output in the screenshot below:

7. Dates
Syntax
Here is the syntax
[datetime]$dateVariable = Get-DateExamples
Here is an example.
[datetime]$currentDate = Get-Date
Write-Output $currentDate # Output: Current date and time
# Specific date
[datetime]$specificDate = [datetime]"2024-01-01"
Write-Output $specificDate # Output: 01 January 2024 00:00:008. Arrays
Syntax
Here is the syntax:
[array]$arrayVariable = @(1, 2, 3, 4, 5)Examples
Here is a simple example of how to use the array data type in PowerShell.
[array]$numbers = @(1, 2, 3, 4, 5)
Write-Output $numbers # Output: 1 2 3 4 5
# Accessing elements
$firstNumber = $numbers[0]
Write-Output $firstNumber # Output: 1
# Adding elements
$numbers += 6
Write-Output $numbers # Output: 1 2 3 4 5 69. Hash Tables
Syntax
Here is the syntax:
$hashTable = @{ Key1 = 'Value1'; Key2 = 'Value2' }Examples
Here is a complete example of how to use the hashtable data type in PowerShell.
$person = @{ Name = "John" Age = 30 Occupation = "Developer"
}
# Accessing values
$name = $person["Name"]
Write-Output $name # Output: John
# Adding key-value pairs
$person["Country"] = "USA"
Write-Output $personYou can see the output in the screenshot below:

10. Custom Objects
Syntax
Here is the syntax of custom objects data type in PowerShell.
$customObject = New-Object PSObject -Property @{ Property1 = 'Value1' Property2 = 'Value2'
}Examples
Here is a simple example to understand about the PowerShell custom objects data type.
$person = New-Object PSObject -Property @{ Name = "Jane" Age = 28 Occupation = "Designer"
}
# Accessing properties
Write-Output $person.Name # Output: Jane
# Adding properties
$person.Country = "Canada"
Write-Output $person How to Check Data Type in PowerShell?
Now, let me show you how to check data type in PowerShell with a few examples.
In PowerShell, you can determine the data type of a variable by using the GetType() method. This method provides detailed information about the variable type, such as its name and base type. Here’s how you can use it:
- Assign a value to a variable:
$x = 10 - Use the
GetType()method to find out the type:$x.GetType()
Here are a few examples to understand this better.
Example 1: Integer Type
The below PowerShell script is to know about the integer type in PowerShell.
$x = 10
$xType = $x.GetType()
Write-Output $xTypeIsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueTypeIn this example, $x is of type Int32, which is an integer.
Example 2: String Type
Here is an example for a string data type in PowerShell.
$str = "Hello, PowerShell!"
$strType = $str.GetType()
Write-Output $strTypeIsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.ObjectHere, $str is of type String.
Example 3: Array Type
Here is an example for a PowerShell array data type.
$arr = @(1, 2, 3)
$arrType = $arr.GetType()
Write-Output $arrTypeIsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.ArrayIn this case, $arr is an array of objects.
Conclusion
I hope you now have an idea of the various data types in PowerShell. I have shown you the syntax and examples of each data type. Here is a summary:
- Integers are used for whole number arithmetic.
- Floats and Doubles handle fractional numbers with varying precision.
- Decimals are crucial for high-precision arithmetic, especially in financial contexts.
- Characters represent single Unicode characters.
- Strings handle text data and support various operations.
- Booleans are used for logical operations and control flow.
- Dates manage date and time information.
- Arrays store collections of items.
- Hash Tables store key-value pairs for efficient lookups.
- Custom Objects represent structured data with multiple properties.
You may also like:
Creating an Empty Array
$array3 = @() $array3.GetType()

Printing an Array
The easiest way to display the contents of an array is to simply reference the array variable. The example below shows how to include the text “Element:” before each item in the array:
To write to a .txt file, use the Out-File command:
$var5 | Out-File C:scriptsarray.txt
To export to a .csv file, use the Export-Csv command:
$var6 | Export-Csv -Path C:scriptsarray.csv
Removing an Item from an Array
Now let’s use an ArrayList to remove an item from an array. First let’s create an array.
$array5 = "one", "two", "three", "four", "five" $array5.gettype()
Now we will add it to an ArrayList so we can easily modify it.
[System.Collections.ArrayList]$ArrayList1 = $array5 $ArrayList1.GetType()
We will then use the .Remove command.
$ArrayList1.Remove("three")
Filtering an Array
We can use the Where-Object cmdlet to retrieve only the even numbers from an array:
$numbers = 1,2,3,4,5,6
$evenNumbers = $numbers | Where-Object { $_ % 2 -eq 0 }
$evenNumbers
Alternatively, we can use the .Where() method, which it does not require a pipeline:
$numbers = 1,2,3,4,5,6
$evenNumbers = $numbers.Where({ $_ % 2 -eq 0 })
$evenNumbersComparing, Grouping, Selecting and Sorting Arrays
Other useful PowerShell cmdlets for working with arrays include:
- Compare-Object — Compares two arrays and returns the differences.
- Group-Object — Groups array elements based on property values.
- Select-Object — Selects specified properties of an object or set of objects, and can also be used to select a specific number of elements from an array.
- Sort-Object — Used to sort arrays that contain only one data type, as shown below:
$array = @(3, 1, 4, 2) $sortedArray = $array | Sort-Object
Checking Whether an Array Contains a Particular Value
If you want to see if any of the elements in an array contains a particular value, use the Contains method. This code will show whether an array contains either a 2 or a 12:
$array7 = 1,2,5,8,3,4,5 $array7.Contains(2) $array7.Contains(12)
Creating a Strongly Typed Array
By default, the elements of an array can have different data types. But you can also create arrays that accept only values of a single designated type. Trying to add a value of a different type will produce an error. Here is how to create the most common strongly typed arrays:
[int[]]$intArray = 1, 2, 3
[string[]]$strArray = "one", "two", "three"
[datetime[]]$dateArray = (Get-Date), (Get-Date).AddDays(1)
But what can you do with it?
In PowerShell, you can store data in a Variable. Depending on what you try to store, it might not be in the correct format for further use in your script. In the chapters below, I will show you the types that I usually use to get things done 😉
[array]
[array]$array=Get-ChildItem
[datetime]
PS C:\Users\HarmVeenstra> $datetime=get-date PS C:\Users\HarmVeenstra> $datetime.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True DateTime System.ValueType
Because it’s in this format, you can use things like:
PS C:\Users\HarmVeenstra> $datetime.DayOfWeek Thursday PS C:\Users\HarmVeenstra> $datetime.Hour 14 PS C:\Users\HarmVeenstra> $datetime.AddHours(-1) donderdag 11 april 2024 13:59:08
[string]
The simplest one is just a simple line of text without any carriage return. For example:
C:\Users\HarmVeenstra> $string="This is just a simple line of text" C:\Users\HarmVeenstra> $string This is just a simple line of text C:\Users\HarmVeenstra> $string.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object
Using “.GetType()” behind the variable will show that the BaseType is System.Object with a String type.
[version]
This is something that I use to compare versions of applications or PowerShell modules. For example:
PS C:\Users\HarmVeenstra> $version='2.3.2' PS C:\Users\HarmVeenstra> $version.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object PS C:\Users\HarmVeenstra> $version 2.3.2
PS C:\Users\HarmVeenstra> [version]$version='2.3.2' PS C:\Users\HarmVeenstra> $version.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Version System.Object PS C:\Users\HarmVeenstra> $version Major Minor Build Revision ----- ----- ----- -------- 2 3 2 -1
[xml]
PS C:\Users\HarmVeenstra> $xml=Get-Content C:\temp\example.xml PS C:\Users\HarmVeenstra> $xml <Configuration ID="1ea22db9-fbc6-4254-aea8-7c5fa6b96b07"> <Add OfficeClientEdition="64" Channel="MonthlyEnterprise" SourcePath="\\test.local\data\software\microsoft\m365" AllowCdnFallback="TRUE"> <Product ID="O365ProPlusRetail"> <Language ID="MatchOS" /> <Language ID="zh-cn" /> <Language ID="hr-hr" /> .....
PS C:\Users\HarmVeenstra> [xml]$xml=Get-Content C:\temp\example.xml
PS C:\Users\HarmVeenstra> $xml.getType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False XmlDocument System.Xml.XmlNode
PS C:\Users\HarmVeenstra> $xml
Configuration
-------------
Configuration
PS C:\Users\HarmVeenstra> $xml.Configuration
ID : 1ea22db9-fbc6-4254-aea8-7c5fa6b96b07
Add : Add
Property : {SharedComputerLicensing, PinIconsToTaskbar, SCLCacheOverride, AUTOACTIVATE…}
Updates : Updates
RemoveMSI : RemoveMSI
AppSettings : AppSettings
Display : Display
Logging : Logging
PS C:\Users\HarmVeenstra> $xml.Configuration.RemoveMSI.IgnoreProduct
ID
--
InfoPath
InfoPathR
PrjPro
PrjStd
SharePointDesigner
VisPro
VisStd
PS C:\Users\HarmVeenstra>Clearing an Array
There is no defined way to delete an array, but there are several ways to get rid of the contents of an array (clear it). One is to assign the variable $null to the array:
$array7 = $null $array7
Here is another way to clear an array:
$array = @("element1", "element2", "element3")
$array = @()Here is how to clear an ArrayList:
$arrayList = New-Object System.Collections.ArrayList
$arrayList.Add("element1")
$arrayList.Add("element2")
$arrayList.Clear()Creating an Array of Objects
By default, each item in an array is an object, rather than another data type like string or integer. Here is an example of how to create an array of objects by explicitly adding objects:
$people = @(
[PSCustomObject]@{Name='Alice'; Age=30},
[PSCustomObject]@{Name='Bob'; Age=25}Creating an ArrayList
For large arrays or frequent additions, use of += can be a performance concern, since every time use it, a new array is created, the old elements are copied over and the new element is added to the end. In those cases, you may want to use an ArrayList.
The size of an ArrayList is mutable, so you can add or remove items without having to recreate the entire collection. Like a standard array, an ArrayList can hold items of different data types.
Here is the cmdlet to create an ArrayList:
$array3 = New-Object System.Collections.ArrayList
Looping through an Array
$array8 = @("Earth","Mercury","Venus","Jupiter","Saturn","Mars", "Neptune", "Pluto")
foreach ($array in $array8) {
"$array = " + $array.length
}The result will look like this:
Adding to an Array
The size of an array in PowerShell is immutable once it is defined. However, the operator += enables you to create a new array by appending items to an existing array — essentially creating a new combined array.
$array = @(1, 2, 3) $array += 4
Using the Replace Operator
The replace operator is used to replace one string with another. Here is the cmdlet structure:
<originalString> -replace <patternToFind>, <replacementString>
Here is an example that will replace “Hello World” with “PowerShell”:
$string = "Hello World" $newString = $string -replace "World", "PowerShell"
Now Netwrix Can Help
Netwrix GroupID empowers you to:
- Automate user provisioning and deprovisioning from your HR information system (HRIS) to Active Directory, Entra ID and SCIM-enabled applications, thereby enabling new employees to quickly be productive and slashing the risk of adversaries taking over stale identities.
- Automatically update directory groups based on changes like an employee’s promotion or shift to another role, as recorded in your HRIS. This automation keeps access rights updated in near real time as required for security and compliance, while saving your IT team time.
- Delegate group and user management to the people who know who should have access to what. Simple workflows enable line-of-business owners to review their groups and approve or deny user access requests, reducing the risk of having over-privileged groups and users in your directory.
- Keep the directory clean and easier to manage with automated user creation, expiration and deletion.
- Maintain and prove compliance with regulations and standards with deep insight, effective automation and clear reporting on groups and members.
![]()

Checking the Length of an Array
To return the number of elements in array, use the .length parameter:
$array6 = 1,2,3,4,5,6 echo $array6.Length
Creating an Array with Just One Element
If you put just one value in a variable, then PowerShell will not create an array. To confirm this, let’s use two scripts and output their data types.
First, we will create an array in PowerShell with five elements:
$array = @(1, 2, 3, 4, 5) $array1.GetType()
Now let’s try to use a similar script to create an array with just one element:
$array1 = 1 $array1.GetType()
As you can see from the output below, PowerShell created an array (System.Array) for the first example script but not the second.
This behavior is particularly concerning if you want to create an array by retrieving objects by executing a particular command, since you do not know in advance how many objects will be returned in the results.
To get around this issue, you can use the , (comma) 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()
We can confirm the creation of the array with the output shown below:
Accessing Items using the Array Index
As with most programming languages, each individual item in a PowerShell array can be accessed by an index. The index of an array starts at zero, so in an array of three items, the first item is at index 0, the second is at index 1, and the third is at index 2.
To access items using the array index, you need to provide the index in square brackets after the array variable. Below is an example showing how to create an array show the second element:
$colors = "Red", "Green", "Blue", "Yellow" $secondColor = $colors[1] Write-Output $secondColor
You can access items from the end of an array by using a negative index. -1 refers to the last item, -2 refers to the second from the last item, etc.
Slicing an Array
You can create a sub-array by specifying a range, as shown here:
$array = 1,2,3,4,5,6,7,8,9 $subset = $array[3..6]
Using the Join Operator and the Split Operator
In PowerShell, the join operator is used to append an array of strings into a single string, optionally using a specified delimiter. Here is an example without a delimiter.
$array = "Power", "Shell" $joined = $array -join "" # Output: "PowerShell"
Here is what it would be with a delimiter:
The split operator essentially does the opposite of the join operator, as shown in the example below:
$string = "apple,banana,grape" $fruits = $string -split ","
Using a Pipeline
The pipeline is used in PowerShell to pass the output of one command as the input to another. When working with arrays, you can use the pipeline to process and manipulate the data in the array and assign the results to a new array or modify the existing one.
Here we will multiply each array item by 2:
$numbers = 1,2,3,4,5
$doubled = $numbers | ForEach-Object { $_ * 2 }
Reversing an Array
Here is an example of how to reverse the order of the elements in an array:
$numbers = 1..5 [Array]::Reverse($numbers)
Creating a Multidimensional Array (Matrix)
By nesting arrays using commas, you can create a structured arrangement of data in rows or columns. Here we create a 3×3 matrix:
What are data or reference types?
There are two ways in which you can find the types being referenced: data or reference. The Microsoft Learn documents refer to it like this:
Other articles refer to it as data types, for example, this article from ScriptRunner: https://support.scriptrunner.com/articles/#!coding/powershell-data-types

