1

Consider the following example. You have a list of server names copied to the clipboard.

How would you quickly create a PowerShell variable containing the list of strings?

Now I know you just wrap the strings seen below in single quotes, but how could this be done programmatically?

Sample:

$list = @(
One
Two
Three
)
1
  • Going to +1 the answer by @AnsgarWiechers since that method works across PowerShell versions. Also a helpful answer, Powershell V5 can do gcb -> Get-Clipboard and there also is a Set-Clipboard. Commented Jan 11, 2016 at 1:02

1 Answer 1

1

You could use the Clipboard class from the System.Windows.Forms namespace:

Add-Type -Assembly System.Windows.Forms | Out-Null

$clp = [Windows.Forms.Clipboard]::GetText() -split "`r`n"

The clipboard content is returned as a single string, so you need to split it at line breaks to get an array of lines.

Another option would be the InternetExplorer.Application COM object:

$ie = New-Object -COM 'InternetExplorer.Application'
$ie.Navigate("about:blank")
while ($ie.ReadyState -ne 4) { Start-Sleep -Milliseconds 100 }

$clp = $ie.Document.parentWindow.clipboardData.getData('text') -split "`r`n"

$ie.Quit()

However, for this to work you must put about:blank in a security zone where you allow programmatic clipboard access for scripts:

Security Settings → Scripting → Allow Programmatic clipboard access

Sign up to request clarification or add additional context in comments.

8 Comments

@PetSerAl Thanks for the heads up. Fixed.
I think I have a faster method. Line 1 in ISE $list = @' then as many lines as you want. Last line is '@ Now $list contains the list of strings. For example, $list.ToUpper()
@user4317867 How exactly would creating a multiline string fetch anything from the clipboard? Not to mention that a multiline string still is a single string, not a list of strings.
@AnsgarWiechers my fault, I was rushing. My aim was to paste multiple lines into the ISE and create a variable with those string. For example, paste into 1.txt then $var = Get-Content 1.txt followed by foreach($a in $var){"something on $a"}
@user4317867 The code I posted already gives you what Get-Content would return without having to take the detour of writing it to a file first. Or did you mean you want a way to paste clipboard text as a variable defining a list of strings into the IDE? That would be an entirely different question than what you asked.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.