Search Tools Links Login

Creating Arrays in Powershell


Arrays are useful in PowerShell because they allow you to store multiple values in a single variable. This can be convenient when you want to pass a group of values to a function, or when you want to manipulate multiple values in a loop.

For example, let's say you want to store a list of server names in a variable and then pass that list to a function that pings each server to see if it is online. You could do this using an array:

$serverList = "server1", "server2", "server3"

foreach ($server in $serverList) {
Test-Connection -ComputerName $server -Quiet
}

You can also use arrays to store the output of cmdlets and functions. For example, the following command stores the results of the Get-Process cmdlet in an array:

$processes = Get-Process

You can then access individual elements of the array using their index, like this:

$processes[0]

This would return the first element of the array (the first process in the list).

In general, arrays can be useful when you need to store and manipulate a large number of values in a structured way.

To create an array in PowerShell, you can use the New-Object cmdlet and specify the type System.Array as follows:

$array = New-Object System.Array

You can also create an array and initialize it with values at the same time, like this:

$array = 1, 2, 3, 4, 5

Or you can use the @() syntax to create an array and specify its values in a comma-separated list:

$array = @(1, 2, 3, 4, 5)

You can also create an array of a specific data type by using the System.Array type and the -Type parameter, like this:

$array = New-Object System.Array -Type int -Dimension 5

This will create an array of integers with 5 elements, all of which are initialized to 0.

You can also create an array of a specific size and initialize it with values using the -Value parameter:

$array = New-Object System.Array -Type int -Dimension 5 -Value 1,2,3,4,5

This will create an array of integers with 5 elements, all of which are initialized to the specified values.

About this post

Posted: 2023-01-09
By: dwirch
Viewed: 141 times

Categories

Tip

Tutorials

Scripting

Powershell

PowerShell Code Cache

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.