pwsh/Get-Clipboard.ps1
function Get-Clipboard { [CmdletBinding()]param() begin { New-Delegate kernel32 { ptr GlobalLock([ptr]) bool GlobalUnlock([ptr]) } New-Delegate user32 { bool CloseClipboard uint EnumClipboardFormats([uint]) ptr GetClipboardData([uint]) bool OpenClipboard([ptr]) } function private:Test-Clipboard([UInt32]$Format) { process { while (0 -ne ($fmt = $user32.EnumClipboardFormats.Invoke($fmt))) { if ($fmt -eq $Format) { return $true } } return $false } } } process {} end { if ($user32.OpenClipboard.Invoke([IntPtr]::Zero)) { Write-Verbose 'clipboard has been successfully opened.' try { if (!(Test-Clipboard 13)) { # CF_UNICODETEXT throw 'clipboard does not contain any textual data.' } if (($data = $user32.GetClipboardData.Invoke(13)) -eq [IntPtr]::Zero) { throw 'clipboard retrieval failed.' } if (($ptxt = $kernel32.GlobalLock.Invoke($data)) -eq [IntPtr]::Zero) { throw 'locking memory failed.' } [Runtime.InteropServices.Marshal]::PtrToStringAuto($ptxt) } catch { Write-Verbose $_ } finally { if ($ptxt) { if (!$kernel32.GlobalUnlock.Invoke($data)) { Write-Verbose 'unlocking memory failed.' } } } if ($user32.CloseClipboard.Invoke()) { Write-Verbose 'clipboard has been successfully closed.' } } else { Write-Verbose 'cannot open clipboard.' } } } Export-ModuleMember -Function Get-Clipboard |