使用PowerShell从剪贴板保存图像

时间:2019-03-18 06:13:04

标签: powershell powershell-v4.0

我正在尝试将图像从剪贴板保存到文件路径。我已经尝试过以下脚本,但返回的消息是“剪贴板不包含图像数据”。

Add-Type -AssemblyName System.Windows.Forms
if ($([System.Windows.Forms.Clipboard]::ContainsImage())) {
    $image = [System.Windows.Forms.Clipboard]::GetImage()
    $filename='e:\test\test.png'         

    [System.Drawing.Bitmap]$image.Save($filename, [System.Drawing.Imaging.ImageFormat]::Png)
    Write-Output "clipboard content saved as $filename"
} else {
    Write-Output "clipboarsd does not contains image data"
}

由于Clipboard类只能在设置为单线程单元(STA)模式的线程中使用。

我尝试在

中运行脚本
powershell -NoProfile -Sta -File $file

此外,如果运行空间不是STA,我还尝试重新启动,这没有帮助。

Add-Type -AssemblyName System.Windows.Forms
if ($host.Runspace.ApartmentState -ne "STA") {
    "Relaunching"
    $file = "./saveImage.ps1"
    powershell -NoProfile -Sta -File $file 
    return
}

1 个答案:

答案 0 :(得分:0)

在PowerShell 5.1中,您可以使用Get-clipboard

set -a; PEM_PATH="/Users/Elasticsearch/Desktop/ec2-poc.pem"; set +a

这也应该起作用:

set -a