assign a variable with a multi line string (array) right in the console

Hello Guys,

This may be a silly question… Is there a way to assign a variable with a multi line string (array) right in the console without getting it from a file or other commands? We work on consoles and often we will quickly copy the text from an excel sheet or some other source and I may want to do something with those data (for example 5 servers which I need to supply to Test-Connection cmdlet). During such cases I always need to store it in the file and use get-content or I need to put a comma in between the servers to make it an array.

I was just wondering is there is a way to just copy and paste the multiline (array) content to console and store it in a variable.

Here is what I tried -

# If the content is stored in a file 

PS [2:45:58 AM] C:\> cat .\test.txt
line1
line2
line3
line4
line5

PS [2:46:02 AM] C:\> $a = cat .\test.txt

PS [2:46:13 AM] C:\> $a | measure


Count    : 5
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property : 

## I am trying the same here directly on the console. 


PS [2:46:20 AM] C:\> $b = 'line1
line2
line3
line4
line5'

PS [2:46:42 AM] C:\> $b | measure


Count    : 1
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property : 

Hadn’t thought of pasting into the console directly - actually seems like a good idea - I might start doing it.

To work around the issue of getting ONE multi-line string object, rather than multiple string objects in an array, you can do something like this:

$b = $b.Split("`n")

… or, more robustly, with a regex to the -split operator (and optionally forcing the type to an array in case you need to support one-line input in PSv2, with “@( stuff )”):

$b = @($b -split '[\r\n]+')

I’ve used these for years, works great! http://www.lazywinadmin.com/2010/06/powershell-get-clipboard-set-clipboard.html.

Add in Joakim’s suggestion and you get this…

function Get-ClipBoard {
    Add-Type -AssemblyName System.Windows.Forms
    $tb = New-Object System.Windows.Forms.TextBox
    $tb.Multiline = $true
    $tb.Paste()
    @($tb.Text -split '[\r\n]+')
}

And away we go!

Get-ClipBoard | %{Test-Connection -ComputerName $_ -Count 1}

I must be so excited I can barely contain myself, because I just put that function in my profile, tested it, and plan to start using it!

$a = while (Read-Host -OutVariable l){$l}

Thank you Joakim & Jack Neff - Thank you. Its awesome. :slight_smile:

Also

function Get-ClipBoard {
Add-Type -Assembly PresentationCore
[Windows.Clipboard]::GetText() -split ‘\r\n’
}

Thankyou Thomas!