Copy to clipboard in script

Product: PowerShell Universal
Version: 4.2.12

First off, I have already seen this forum post about Set-UDClipboard, along with this documentation, but I am looking for a solution for copying to a clipboard in a script, not a dashboard.

I need to use a third-party module which unfortunately is only able to return some data via a clipboard. This has been working fine in PS 7 in any environment (command line, PSU dashboard, PSU script). However in our production environment we have several scripts running on PS 5.1.17763.5830, and anytime I try to set the clipboard it errors out. When using the third-party function, it returns nothing (probably due to some internal error handling), but when I run a basic Set-Clipboard it throws an error.

Here is the test script I am running:

$str = 'abc123'
$Result = $null
Set-Clipboard $str
$str = '34734563asdfasd'
$Result = Get-Clipboard
echo "Result: $Result"
Set-Clipboard $null

When running the above in PS 7, it works perfectly, but when running it in 5.1 it throws the following error:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

Also, when running the same code on the command line of the PSU server there is about a 50/50 that it actually works. Set-Clipboard often fails and throws this error

Requested Clipboard operation did not succeed.
    + CategoryInfo          : NotSpecified: (:) [Set-Clipboard], ExternalException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.ExternalException,Microsoft.PowerShell.Commands.SetClipboardCommand

Running this on my local PS 5.1.22621.3672 works perfectly as well.

I have also tried using Set-UDClipboard, but it throws this error:

[error] You cannot call a method on a null-valued expression.

Does anybody know of way to consistently copy data to a clipboard in PS 5.1?

I did some more investigating and I found the code that the third-party software uses for setting a clipboard. The core functionality is the same, but I tweaked it for better testing:

$value = 'abc123'
$Output = $null
if ([System.Threading.Thread]::CurrentThread.GetApartmentState() -eq [System.Threading.ApartmentState]::MTA) {
    powershell -sta "Set-Clipboard -Value '$value'"
} else {
    Set-Clipboard -Value $value
$Output = Get-Clipboard
echo "Result: $Output"

When I run that code on the command line of the PSU server, it works great. However when I run it as an automated PS 5.1 script from PSU, it returns null. The ApartmentState is MTA for an automated script, but its the same on the command line and it still works.

I am not sure what is causing this, but I am still looking into it