Pasting Multiple Lines in PowerShell

by Jul 13, 2022

When you copy multiple lines of PowerShell code and paste them into a shell window, the result often is not what you expect. PowerShell starts executing the first line and won’t execute the pasted code en bloc. Try and look at the default behavior by copying the code below, then pasting it into a PowerShell console window:

"Starting!"
$a = Read-Host -Prompt 'Enter something'
"Entered: $a"
"Completed"

Each line of the pasted block is executed individually which you can see when you look at the prompt displayed before each output line.

While this default behavior can be OK, if you must ensure that your entire code block is executed in one, embed it into curly brackets and execute this script block with the “.” operator. Try and copy this embedded code:

. {
"Starting!"
$a = Read-Host -Prompt 'Enter something'
"Entered: $a"
"Completed"
}

When you paste this code, it executes e n bloc just as if it was stored and loaded from a script file.


Twitter This Tip! ReTweet this Tip!