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
1 2 3 4 5 6 7 8 9 |
$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.
1 2 3 4 5 6 7 8 9 |
#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 |
This was just what I needed, thank you!