rplantiko
rplantiko

Reputation: 2738

Pass a DataObject in PowerShell to clipboard

My plan is to write a PowerShell script as a utility which

To check whether this is viable, I wrote the following explorative script

$text = "test"        # <-- will finally simply echo the current clipboard content
$html = "<b>test</b>" # <-- will finally contain enriched text/html data, based on $text

$new = New-Object System.Windows.Forms.DataObject
$new.SetData([System.Windows.Forms.DataFormats]::Html, $html)
$new.SetData([System.Windows.Forms.DataFormats]::Text, $text)
[System.Windows.Forms.Clipboard]::SetDataObject($new)
  
# --- Test: have the strings $text and $html been placed in the clipboard? 
$act = [System.Windows.Forms.Clipboard]::GetDataObject( )
Write-Output "formats:" 
Write-Output $act.GetFormats()      
Write-Output( "html:--"+$act.GetData([System.Windows.Forms.DataFormats]::Html)+"--" )  
Write-Output( "text:--"+$act.GetData([System.Windows.Forms.DataFormats]::Text)+"--" )  

Unfortunately, the test strings are not transported into the clipboard (though the script is not completely ignored, as the clipboard contains the text/html entry afterwards):

PS C:\****\powershell> ./test-clip-add-html.ps1
formats:
System.String
UnicodeText
Text
HTML Format        # <<< this has been added, ok 
html:----          # expected: --<b>test</b>--
text:----          # expected: --test-- 

What am I missing to transfer the string contents into the clipboard data object?

Upvotes: 0

Views: 51

Answers (2)

rplantiko
rplantiko

Reputation: 2738

After santiago-squarzon informed me that it worked for him, I looked for other stack overflows where there was somehow a load problem for the involved system class.

I found out that adding the line

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

at the beginning of the script, the access to the clipboard worked as it should, and the script produced the expected output.

Upvotes: 0

Vern_Anderson
Vern_Anderson

Reputation: 100

Get-Command -Noun *CLIP*

CommandType     Name                                               Version    Source                                                                                                                                                        
-----------     ----                                               -------    ------                                                                                                                                                        
Cmdlet          Get-Clipboard                                      3.1.0.0    Microsoft.PowerShell.Management                                                                                                                               
Cmdlet          Set-Clipboard                                      3.1.0.0    Microsoft.PowerShell.Management    

Upvotes: 0

Related Questions