How to get the array as input using Powershell

To read an array into Read-Host (get the array as input), you would need to put it in a loop because anything entered into Read-Host will be interpreted as a string. To make output in new line we can use $OFS, which is a special variable in PowerShell . OFS stands for Output field separator . You would use this to separate object/Array.

The .split() method is self explanatory, the .trim() method will simply remove leading and trailing spaces and leading and trailing line breaks

Example #1 : Getting Value as an Array by Looping

$arrayInput = @()
do {
$input = (Read-Host "Please enter the Array Value")
if ($input -ne '') {$arrayInput += $input}
}
#Loop will stop when user enter 'END' as input
until ($input -eq 'end')

$arrayInput

OUTPUT:

Example 2# : Alternative approach for handling the multiple inputs without loop.

#Set New line using OFS special Powershell variable
$OFS = "`n"
#Externally set input value as string
[string[]] $_ServerList= @()
#Get the input from the user
$_ServerList = READ-HOST "Enter List of Servers"
#splitting the list of input as array by Comma & Empty Space
$_ServerList = $_ServerList.Split(',').Split(' ')
$OFS + $_ServerList

Output:

One thought on “How to get the array as input using Powershell”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.