Two of my favorite cmdlets from the PowerShell Community Extensions are
out-clipboard. These cmdlets let you read from and write to the Windows clipboard from PowerShell. For example, the following code will grab the contents of the clipboard, replace every block of white-space with a comma, and paste the result back to the clipboard.
(get-clipboard) -replace 's+(?!$)', ',' | out-clipboard
I saved this to a file
comma.ps1 in my path and run it when I get a list of numbers from one program delimited by newlines or tabs and need to make it the input to another program expecting comma-delimited values. For example, turning a column of numbers into an array for R. I copy one format, run
comma.ps1, and paste in the new format.
In case you’re curious about the mysterious characters in the script,
s+(?!$) is a regular expression describing where I want to substitute a comma. The
s refers to white-space characters (tabs, spaces, newlines) and the
+says this is repeated one or more times. So match one or more consecutive white-space characters. That would be enough by itself, but it would replace trailing white-space with a comma too, so I might get an unwanted comma at the end. The sequence
(?!$) fixes that. The
$ matches the end of line. The
(?! before and the
) after form a negative look ahead, meaning “except when the thing inside matches.” So taken all together, the regular expression matches chunks of white-space except at the end of the input.
Update: See Manipulating the clipboard with PowerShell