powershell - Powershell 脚本中的参数

标签 powershell imagemagick imagemagick-convert

我尝试用 imageick 处理图片。在 CLI 上,我使用这个工作正常的命令:

C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe D:\orG\3.08_10-02_1.jpg -resize 1200x1200 D:\orG\output\3.08_10-02_1.jpg

但我尝试在 powershell 脚本 (test.ps1) 中使用以下代码:

$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'
$arg2 = 'D:\orG\3.08_10-02_1.jpg'
$arg3 = '-resize 1200x1200'
$arg4 = 'D:\orG\output\3.08_10-02_1.jpg'

& $CMD $arg2 $arg3 $arg4 

我收到此错误:magick.exe:在 CLI arg 2 @ fatal/magick-cli.c/ProcessCommandOptions/659 处无法识别选项“-resize 1200x1200”。

我也尝试过:

$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'
$arg1 = 'convert'
$arg2 = 'D:\orG\3.08_10-02_1.jpg'
$arg3 = '-resize 1200x1200'
$arg4 = 'D:\orG\output\3.08_10-02_1.jpg'

& $CMD $arg1 $arg2 $arg3 $arg4 

但错误类似:convert: unrecognized option `-resize 1200x1200' @ error/convert.c/ConvertImageCommand/2686。

如果我删除选项“-resize 1200x1200”。现在出现错误消息,并且该命令正在将文件(不调整大小)写入输出文件夹。所以我认为我的选择有问题,但我找不到它。我投入了几个小时,并尝试使用 @ 符号作为参数,但没有成功。

最佳答案

您必须分隔参数名称和值,否则-resize 1200x1200将作为单个标记传递,但 native 可执行文件通常期望参数名称和值是分开的标记(除非语法没有空格,例如 -name:value)。

$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'
$arg1 = 'convert'
$arg2 = 'D:\orG\3.08_10-02_1.jpg'
$arg3 = '-resize', '1200x1200'
               # |<-- inserted comma here
$arg4 = 'D:\orG\output\3.08_10-02_1.jpg'

& $CMD $arg1 $arg2 $arg3 $arg4 

这会将 $arg3 转换为两个字符串的数组,PowerShell 将其作为单独的参数标记传递。这也称为splatting,并且仅在调用 native 可执行文件时完成(对于 PowerShell 命令,您必须使用 @ splatting 运算符)。

另一种更简洁的方式:

$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'

# Create an array of arguments
$imArgs = @(
    'convert'
    'D:\orG\3.08_10-02_1.jpg'
    '-resize', '1200x1200'
    'D:\orG\output\3.08_10-02_1.jpg' 
)

# Call native command, which splats argument array.
& $CMD $imArgs

# Alternatively you can be explicit about splatting:
& $CMD @imArgs

确保您没有将变量命名为 $args,它是保留的 PowerShell 变量。


顺便说一句,如果您希望能够调用 ImageMagick 而不必在所有脚本中硬编码其路径,请添加 ImageMagick 的安装目录(“C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable” -Q16-HDRI-x64") 到 PATH 环境变量。

然后您只需指定其可执行文件的名称即可调用 ImageMagick:

magick @imArgs

关于powershell - Powershell 脚本中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75499385/

相关文章:

powershell - 从 PowerShell 打开 Notepad++

powershell 远程处理 Win2008R2 "The WSMan service could not launch a host process to process the given request"

imagemagick - 定义 ImageMagick 转换的文件顺序

ruby-on-rails - 如何在 Shrine 中调整原始图像本身的大小上传

php - Imagemagick convert -fill 不会改变特定调色板区域的边缘

linux - 让 imagemagick 在共享主机上工作

powershell - cmd.exe 抛出错误 "& was unexpected at this time."

powershell - 从Windows CMD将数组传递到PowerShell

imagemagick - 使用 ImageMagick 在没有输出文件扩展名的情况下将 PDF 转换为 PNG

python - ImageMagick 魔杖无法识别 pdf 图像?