How to Print Arrays in PowerShell?

Arrays are a fundamental data structure in any programming language, and PowerShell is no exception. An array is a collection of items accessed by their index or iterated over. PowerShell makes it easy to work with arrays, whether you’re storing a list of names, numbers, or more complex objects. I will explain how to print arrays in PowerShell in this PowerShell tutorial.

Print Arrays in PowerShell

Before you print an array in PowerShell, you must declare and initialize it. Here’s how you can create an array in PowerShell:

# Declaring an array with explicit values
$myArray = @(1, 2, 'three', 'four')

# Declaring an array with a range of numbers
$numberArray = 1..10

Basic Printing of Arrays

The simplest way to print an entire array in PowerShell is to use the Write-Output cmdlet or its alias echo. When you pass an array to Write-Output, PowerShell will print each item on a new line.

# Printing an array with Write-Output
Write-Output $myArray

You can also see the output in the screenshot below after I executed the code using Visual Studio Code.

Print Arrays in PowerShell

Accessing Individual Items

Sometimes, you may want to print a specific item from an array. You can do this by specifying the index of the item:

# Printing the first item of the array
Write-Output $myArray[0]

# Printing the third item of the array
Write-Output $myArray[2]

Remember, PowerShell arrays are zero-indexed, which means the first item is at index 0.

Looping Through Arrays

To print each item in an array, you can loop through the array using a foreach loop:

# Using foreach to print each item
foreach ($item in $myArray) {
    Write-Output $item
}

Advanced Printing with Custom Formatting in PowerShell

If you need to print your array in PowerShell with custom formatting, you can use a foreach loop in combination with string formatting:

# Printing each item with custom formatting
foreach ($item in $myArray) {
    Write-Output "Item: $item"
}

Joining Array Elements

Another way to print an array is to join the elements into a single string in PowerShell. You can use the -join operator for this purpose:

# Joining array elements with a comma
$joinedArray = $myArray -join ', '
Write-Output $joinedArray

Exporting Arrays to a File

If you want to print your array to a file in PowerShell, you can use the Out-File cmdlet:

# Exporting array to a text file
$myArray | Out-File -FilePath C:\path\to\your\file.txt

Conclusion

Printing arrays in PowerShell is straightforward. Whether you’re printing the entire array, specific elements, or iterating through each item, PowerShell provides the flexibility to display the data.

In this PowerShell tutorial, I have explained different ways to print an array in PowerShell.

You may also like: