I’ve started working on the 2nd edition of Managing Active Directory with Windows PowerShell: TFM. As with almost all of my writing projects it will be full of PowerShell code examples. In the past I’ve always relied on a manual copy and paste to add content to the manuscript. The PowerShell Community Extensions made this a little easier in the past with their Out-Clipboard cmdlet. That made it easier to grab the results so I could paste them in my Word document. But I also needed the PowerShell command which meant another copy and paste. What I really needed was a way to grab the expression AND the result and send both to the Windows clipboard. Thus was born Out-Clip.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
1: Function Out-Clip {
2:
3: <#
4: .Synopsis
5: Capture a PowerShell command and its result to the Windows clipboard.
6: .Description
7: Using Write-Clipboard from the PowerShell Community Extensions,
8: this function will take a Windows PowerShell scriptblock, execute
9: it and write both the command and the results to the Windows clipboard.
10:
11: You can also pipe a collection of scriptblocks to this function or use
12: a comma separated list with the -Scriptblock parameter.
13:
14: By default the output will include the PS prompt set to PS C:\>.
15: If you want to use the actual current location then specify
16: -UseCurrentLocation. If you prefer no prompt at all then use -NoLocation.
17: .Parameter ScriptBlock
18: The scriptblock command you wish to execute.
19: .Parameter UseCurrentLocation
20: Use the current location for the prompt instead of PS C:\>
21: .Parameter NoLocation
22: Do not include any prompt information. Only display the
23: script block and results.
24: .Example
25: PS C:\> Out-Clip {get-process | where {$_.ws -gt 50MB}}
26: .Example
27: PS C:\Users\Jeff\Documents\> Out-Clip {dir -recurse -filter *.doc} -UseCurrentLocation
28: .Example
29: PS C:\Work\> {get-process},{get-service} | Out-Clip -nolocation
30: .Inputs
31: A scriptblock
32: .Outputs
33: None
34: .Link
35: Write-Clipboard
36: Set-Clipboard
37: Out-Clipboard
38: Get-Clipboard
39: .Notes
40: Version : 1.0
41: Name : Out-Clip
42: Last Update: 7/6/2010
43: URL : https://jdhitsolutions.com/blog
44: #>
45:
46: [cmdletBinding(DefaultParameterSetName="Location")]
47:
48: Param(
49: [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$True,
50: HelpMessage="Enter a PowerShell expression")]
51: [ValidateNotNullorEmpty()]
52: [scriptblock[]]$ScriptBlock,
53: [Parameter(ParameterSetName="Location")]
54: [switch]$UseCurrentLocation,
55: [Parameter(ParameterSetName="NoLocation")]
56: [switch]$NoLocation
57: )
58:
59: Begin {
60: Write-Verbose "Starting $($myinvocation.mycommand)"
61:
62: Try {
63: Write-Verbose "Verifying Write-Clipboard"
64: Get-Command -Name "Write-Clipboard" -ErrorAction "Stop" | Out-Null
65: }
66:
67: Catch {
68: Write-Warning "Failed to find Write-Clipboard from the PowerShell Community Extensions."
69: Break
70: }
71: #define prompt to display, if any
72: if ($NoLocation) {
73: Write-Verbose "NoPrompt specified"
74: $myPrompt=""
75: }
76: elseif ($UseCurrentLocation) {
77: Write-Verbose "Using current location $($pwd)"
78: $myPrompt="PS $pwd\> "
79: }
80: else {
81: Write-Verbose "Using default prompt"
82: $myPrompt="PS C:\> "
83: }
84:
85: #initialize an array to hold results
86: Write-Verbose "Initializing output array"
87: $output=@{}
88: } #close Begin
89:
90: Process {
91: foreach ($sb in $scriptblock) {
92: #run the command and save the result
93: Write-Verbose "Executing scriptblock"
94: Write-Verbose $sb.ToString()
95: $result=&$sb
96:
97: #check if the command succeeded. If not, then get the
98: #last exception and make it the result
99: if (-not $result) {
100: Write-Verbose "Adding exception"
101: $result=$error[0]
102: }
103: Write-Verbose "Building data and adding to hash table"
104: #define the first line with the prompt and command
105: $commandline="{0}{1}" -f $myPrompt,$sb.ToString()
106: #add the command and results to the hash table
107: $output.Add($commandline,($result | out-string))
108: } #foreach $sb in $scriptblockl
109: } #close Process
110:
111: End {
112: Write-Verbose "Writing output to the clipboard"
113: #enumerate the keys and then the command results
114: $output.keys | foreach {$_,($output.item($_) | out-string)} | write-clipboard
115: Write-Verbose "Command and results written to the clipboard."
116: Write-Verbose "Ending $($myinvocation.mycommand)"
117: } #close end
118:
119: } #end function
The function requires the Write-Clipboard cmdlet from the PowerShell Community Extensions. I use a Try/Catch block to verify the cmdlet exists in your current session. If it doesn’t, you get an error message and the pipeline is terminated. You’ll need to make sure you manually load the module before running this function.
The function itself is pretty basic I think. You can specify one or more scriptblocks either with the –Scriptblock parameter or piped into the function.
PS C:\> out-clip {get-service spooler | select *}
Since I prefer almost all of my code examples to use a prompt of PS C:\>, the function prepends it before the scriptblock command. If you prefer to see the actual or current location, use the –UseCurrentLocation parameter. If you prefer no prompt, then use –NoLocation. Because these two values are mutually exclusive, I’ve used two parameter sets, which you can see when you look at help.
PS C:\> get-help out-clip
NAME
Out-Clip
SYNOPSIS
Capture a PowerShell command and its result to the Windows clipboard.
SYNTAX
Out-Clip [-ScriptBlock] <ScriptBlock[]> [-UseCurrentLocation] [<CommonParameters>]
Out-Clip [-ScriptBlock] <ScriptBlock[]> [-NoLocation] [<CommonParameters>]
DESCRIPTION
Using Write-Clipboard from the PowerShell Community Extensions,
this function will take a Windows PowerShell scriptblock, execute
it and write both the command and the results to the Windows clipboard.
You can also pipe a collection of scriptblocks to this function or use
a comma separated list with the -Scriptblock parameter.
By default the output will include the PS prompt set to PS C:\>.
If you want to use the actual current location then specify
-UseCurrentLocation. If you prefer no prompt at all then use -NoLocation.
RELATED LINKS
Write-Clipboard
Set-Clipboard
Out-Clipboard
Get-Clipboard
REMARKS
To see the examples, type: "get-help Out-Clip -examples".
For more information, type: "get-help Out-Clip -detailed".
For technical information, type: "get-help Out-Clip -full".
Out-Clip uses a hash-table to store the scriptblock command and the result. If the scriptblock fails, then the last error is grabbed and used instead for the result. Thus I always get the command and result in the clipboard, even if the command failed. After all scriptblocks have been evaluated the hash-table’s contents are piped to Write-Clipboard.
1: End {
2: Write-Verbose "Writing output to the clipboard"
3: #enumerate the keys and then the command results
4: $output.keys | foreach {$_,($output.item($_) | out-string)} | write-clipboard
5: Write-Verbose "Command and results written to the clipboard."
6: Write-Verbose "Ending $($myinvocation.mycommand)"
7: } #close end
The script file also defines an alias, oc, for the function since I don’t like to type anymore than I have to.
Granted, this function meets a pretty specific need, but it does demonstrate some PowerShell 2.0 scripting features such as multiple parameter sets, Try/Catch and hash tables. If you try it out, I hope you’ll let me know what you think.
1 thought on “Out-Clip”
Comments are closed.