在PowerShell中将参数作为字符串传递给Call运算符(&)

lx0bsm1f  于 2022-12-04  发布在  Shell
关注(0)|答案(1)|浏览(180)

我有一个PowerShell脚本,在其中我使用Call运算符运行带有一组参数/选项的mkvmerge.exe。我希望将选项收集到一个字符串中,以便可以根据脚本中前面的输入扩展该字符串,但当目标文件位于此字符串中时,mkvmerge由于某种原因无法识别它。我不确定这是因为变量扩展还是什么问题
下面的代码说明了这个问题。我也尝试过将选项添加到数组中并使用@操作符,但没有成功

$mkvmerge = "C:\Program Files\MKVToolNix\mkvmerge.exe"
$applyoptions = $true
$subtitleformat = "srt"
$isolanguage = "eng"

foreach ($file in Get-ChildItem -File -Include *.mkv) {

    <# Make the string with options for mkvmerge #>
    $mkvmergeparams = ""
    if ($applyoptions -eq $true) {
$mkvmergeinstructions += ('`' + "@options.json")
}
    $mkvmergeparams += ("-o " + "`"" + $file.DirectoryName + "\Remux-" + $file.BaseName + ".mkv`" " + "`"" + $file + "`"")
    if (-not($subtitleformat -eq "")) {
$mkvmergeinstructions += (" --default-track " + $subtitledefault) + " --language " + "0:" + $isolanguage + " " + "`"" + $file.DirectoryName + "\" + $file.BaseName + "." + $subtitleformat + "`""
}

    <# Check the string #>
    Write-Host $mkvmergeparams

    <# This does not work, but I would like it to #>
    & $mkvmerge $mkvmergeparams

    <# This works, but would require a separate line for each set of possible options #>
    #& $mkvmerge `@options.json -o ($file.DirectoryName + "\" + "Remux-" + $file.BaseName + ".mkv") $file --default-track $subtitledefault --language ("0:" + $isolanguage) ($file.DirectoryName + "\" + $file.BaseName + "." + $subtitleformat)

}
Read-Host -Prompt "Press enter to exit"

在第二个示例中,变量被展开,mkvmerge识别给定的选项,但这需要为每组可能的输入设置单独的mkvmerge行
检查字符串时,它似乎完全按照预期展开

kuhbmx9i

kuhbmx9i1#

找到了答案。我必须创建一个数组

<# Build array with options for mkvmerge #>
        $mkvmergeparams = $null
        if ($applyoptions -eq $true) {$mkvmergeparams += @('@options.json')}
        $mkvmergeparams += @("-o", ($file.DirectoryName + "\Remux-" + $file.BaseName + ".mkv"), $file)
        if (-not($subtitleformat -eq "")) {$mkvmergeparams += @("--default-track", $subtitledefault, "--language", ("0:" + $isolanguage), ($file.DirectoryName + "\" + $file.BaseName + "." + $subtitleformat))}

相关问题