【问题标题】:Powershell parameter $args[0] with quotesPowershell 参数 $args[0] 带引号
【发布时间】:2015-02-02 16:11:38
【问题描述】:

我正在运行一个从批处理中调用的 PowerShell 脚本,该批处理将文件名作为第一个参数传递。 在我使用的脚本中:

$file = Get-Item -LiteralPath $args[0]

但当文件名包含引号(即:my'file.txt)时,get-item 会触发错误。我试图删除-LiteralPath 参数,但问题是一样的。 脚本的语法是

$file = Get-Item -LiteralPath $args[0] 写主机 $file cmd /c 暂停

如果我针对 my'file.txt 运行脚本,我会得到:

  • C:\m\tag\testscript.ps1 'C:\m\tag\my'file.txt'
  • CategoryInfo : ParserError: (:String) [], ParentContainsErrorRecordException
  • FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

【问题讨论】:

  • 了解错误是什么很有用。如果在调用 Get-Item 之前删除了该引号,那么您将收到 FileNotFound 类型异常,这不是 PowerShell 的错误,但可能是正在消耗该字符的批处理。
  • Thnaks Matt:我收到一条错误消息,提示 TerminatorExpectedAtEndOfString。我正在就我的问题提供更多细节

标签: powershell


【解决方案1】:

假设您在文件批处理中以这种方式传递路径:

powershell.exe  C:\path\myscript.ps1 "%1%"

你需要转义引用:

powershell.exe  C:\path\myscript.ps1 \"%1%\"

【讨论】:

    【解决方案2】:

    你是如何传递参数的?

    这行得通:

    .{gi -literalpath $args[0]} "my'file.txt"
    

    【讨论】:

      【解决方案3】:

      我认为,当 PowerShell 看到文件名时,cmd 可能已经去掉了任何环绕的双引号,因此 PowerShell 将单独的单引号视为解析错误。尝试像这样指定文件名

      my''file.txt
      

      【讨论】:

        猜你喜欢
        • 2014-04-08
        • 1970-01-01
        • 1970-01-01
        • 2013-12-04
        • 2019-08-07
        • 1970-01-01
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        相关资源
        最近更新 更多