【问题标题】:Powershell variable for cmd argumentcmd 参数的 Powershell 变量
【发布时间】:2013-05-23 13:59:21
【问题描述】:

我想为 cmd 参数使用 powershell 变量,但我不知道如何制作它。

function iptc($file)
{        
        $newcredit = correspondance($credit)
        $cmd = '& C:\exiftool\exiftool.exe -S -t -overwrite_original -Credit=$newcredit $file.FullName'
        Invoke-Expression $cmd
}

例如 newcredit 可以是“James”,但在我运行命令时 -Credit 只会是“$newcredit”。

问候

【问题讨论】:

  • 单引号 (' ') 不会扩展变量值。改用双引号 (" ") 或使用字符串格式 (-format)。
  • 非常感谢它现在可以使用了!

标签: powershell parameters cmd arguments


【解决方案1】:

单引号 (' ') 不会扩展字符串中的变量值。您可以使用双引号 (" ") 来解决这个问题:

$cmd = "& C:\exiftool\exiftool.exe -S -t -overwrite_original -Credit=$newcredit $file.FullName"

或者,通过我最常用的方法,使用字符串格式化:

$cmd = '& C:\exiftool\exiftool.exe -S -t -overwrite_original -Credit={0} {1}' -f $newcredit, $file.FullName

如果任一参数中有空格,则该参数需要在输出中用双引号括起来。在那种情况下,我肯定会使用字符串格式:

$cmd = '& C:\exiftool\exiftool.exe -S -t -overwrite_original -Credit="{0}" "{1}"' -f $newcredit, $file.FullName

【讨论】:

  • 谢谢。我还有一个问题,当 $newcredit 由 2 个单词组成时(例如“James Bond”),-Credit 只包含“James”,请问我该怎么办?
  • 谢谢它的工作,但我必须在双引号中加上一个反引号以获得新的信用:-Credit="{0}" 否则它不起作用,现在如果我有两个空格它不起作用或者如果有不是任何空间,它会像"James"`,很奇怪。据我所知,这太难了:link
  • 如果您必须转义字符串内的双引号,那么您必须在字符串外部使用双引号。如果参数中的双引号导致 exiftool 阻塞,那么您不能为该程序提供带空格的参数。您是否完全按照我发布的路线运行?
  • 是的,我完全按照您发布的路线运行,但出现错误:+ CategoryInfo : ParserError: (:String) [Invoke-Expression], IncompleteParseException + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString,Microsoft.PowerShell.Commands.InvokeExpressionCommand
  • 在您的脚本中添加一行,将 Write-Host $cmd 输出到控制台。复制并粘贴它吐出的内容。该命令会执行吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2012-10-16
  • 2011-08-21
  • 2017-12-01
  • 2018-10-28
相关资源
最近更新 更多