Search code examples
windowspowershellclipboard

Adding a string to the Windows clipboard without adding it to the history in PowerShell?


I am using PowerShell to copy sensitive information to the Windows clipboard.

Since Windows 10 Vs. 1809 we have the enhanced clipboard with a history function. I don't want to have my sensitive information in the history.

The Set-Clipboard cmdlet doesn't have any helpful parameters. Even in C# I doesn't seem to have an easy way to do this.


Solution

  • It turns out you can access the Universal Windows Platform (UWP) APIs directly in PowerShell:

     Function Set-ClipboardWithoutHistory([string]$Value)
     {
         [int]$RequestedOperationCopy = 1
    
         $null = [Windows.ApplicationModel.DataTransfer.DataPackage,Windows.ApplicationModel.DataTransfer,ContentType=WindowsRuntime]
         $null = [Windows.ApplicationModel.DataTransfer.ClipboardContentOptions,Windows.ApplicationModel.DataTransfer,ContentType=WindowsRuntime]
         $null = [Windows.ApplicationModel.DataTransfer.Clipboard,Windows.ApplicationModel.DataTransfer,ContentType=WindowsRuntime]
    
         $dataPackage = [Windows.ApplicationModel.DataTransfer.DataPackage]::new()
    
         $cOptions = [Windows.ApplicationModel.DataTransfer.ClipboardContentOptions]::new()
         $cOptions.IsAllowedInHistory = $false
         $cOptions.IsRoamable = $false
    
         $dataPackage.RequestedOperation = $RequestedOperationCopy
         $dataPackage.SetText($Value)
    
         [Windows.ApplicationModel.DataTransfer.Clipboard]::SetContentWithOptions($dataPackage, $cOptions) | Out-Null
     }