使用 PowerShell 从剪贴板保存图像

Pro*_*tor 5 powershell powershell-4.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"
}
Run Code Online (Sandbox Code Playgroud)

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

我试图在

powershell -NoProfile -Sta -File $file
Run Code Online (Sandbox Code Playgroud)

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

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

tho*_*her 9

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

 get-clipboard -format image
 $img = get-clipboard -format image
 $img.save("c:\temp\temp.jpg")
Run Code Online (Sandbox Code Playgroud)

这也应该有效:

Add-Type -AssemblyName System.Windows.Forms
$clipboard = [System.Windows.Forms.Clipboard]::GetDataObject()
if ($clipboard.ContainsImage()) {
    $filename='c:\temp\test3.png'         
    [System.Drawing.Bitmap]$clipboard.getimage().Save($filename, [System.Drawing.Imaging.ImageFormat]::Png)
    Write-Output "clipboard content saved as $filename"
} else {
    Write-Output "clipboard does not contains image data"
}
Run Code Online (Sandbox Code Playgroud)

  • 第一个片段的小优化: > $img = Get-Clipboard -format image if(!$img) { Write-Host "剪贴板中没有文件。" return } $img.save("D:\Temp\temp.jpg") (2认同)