Search code examples
powershellcopy-paste

How to make the input not automatically execute when I paste in PowerShell


I have a feeling that this is a very simple fix, but whenever I try to paste into PowerShell using right-click, it automatically executes whatever it is I am trying to paste. The function is finding a computer name based on an input using AD and then copies the computer name to use in other functions. Here is the code for only the part that does the copying:

    $strComputer = $output.Name
    $strComputer | clip | Out-Null

So when I right-click to paste, it executes whatever $strComputer equals and obviously throws an error. Thanks!


Solution

  • The problem with pasting something into PowerShell (and clip.exe is very good example) is the fact, that any newline (and clip.exe used like that will add newline at the end) will trigger same reaction that you pressing enter would.

    There are at least two ways around it:

    • paste without newlines (e.g. use [System.Windows.Clipboard]::SetText($output.Name))
    • if you are on v3 - use PSReadLine module and CTRL+V

    For the first one - be sure to run Add-Type -AssemblyName PresentationCore first - this assembly is loaded by default only in PowerShell ISE. If you are on v3+ though I would really recommend to give PSReadLine a try.