<<< Back to Search

Declare Array initializing elements

Arrays are used to store a collection of data, but it is often more useful to think of an array as a collection of variables or objects.

On this example array is declared by initializing some Elements on declaration line

Example

# Declare array and initialize elements
$myArray = @("Banana","Apple","Lemon") 

# Add more elements at the end
$myArray += "Watermelon"

# Write Array to host Option 1: Convert array to string before write
Write-Host "Write Array to host:`r`n"

$tempStr = $myArray | Out-String
Write-host $tempStr


# Write Array to host Option 2: piping output
Write-Host "`r`nWrite array piping output:`r`n"
$myArray | Out-String | Write-Host


Output

PS C:\> 

Write Array to host:

Banana
Apple
Lemon
Watermelon


Write array piping output:

Banana
Apple
Lemon
Watermelon