【问题标题】:Powershell call cmd.exe command like copy /bPowershell 调用 cmd.exe 命令,如复制 /b
【发布时间】:2020-11-15 21:48:31
【问题描述】:

我已经看到了Fast and simple binary concatenate files in Powershell

我对上面的答案不感兴趣我对下面的语法有什么问题感兴趣:

当我调用像copy /b 这样的cmd.exe 命令时:

function join-file {
   copy /b $($args[0])+$($args[1]) $($args[2])
}

我收到一个错误Copy-Item : A positional parameter cannot be found

【问题讨论】:

    标签: powershell cmd


    【解决方案1】:

    正如错误所暗示的,copy 实际上只是Copy-Item 的别名,它没有/b 参数。你可以调用 cmd 来使用它的复制命令。

    function join-file {
       cmd /c copy /b $($args[0])+$($args[1]) $($args[2])
    }
    

    【讨论】:

      【解决方案2】:

      注意:这个答案是对Doug Maurer's helpful answer 的补充,它提供了一个有效的解决方案(对于没有空格的文件名)。

      PowerShell 解析 未引用 复合标记(例如 $($args[0])+$($args[1]))的方式有一个微妙之处(复合标记是指直接连接的不同语法结构):

      $($args[0])+$($args[1]) 导致 两个 参数[1] - 尽管手头有特定的命令(cmd.exe 的内部 @ 987654327@ 命令)发生 不是 是一个问题:

      • 参数1:$($args[0])的值

      • 论据 2:逐字逐句 + 后跟 $($args[1]) 的值

      为避免此问题,请将整个复合标记包含在"..." 中,以便可以预见地将其视为expandable string


      结果:

      • 为了安全起见,明确使用双引号 ("...") 将涉及变量引用或子表达式的复合标记括起来

      • 相比之下,引用一个变量甚至方法调用孤立地,既不引用也不包含在$(...)中,需要subexpression operator

      天真地应用于您的命令(请参阅下面更好的解决方案):

      # Note: See better solution below.
      function join-file {
         # Note the "..." around the first argument, and the absence of quoting
         # and $(...) around the second.
         cmd /c copy /b "$($args[0])+$($args[1])" $args[2]
      }
      

      但是,如果$args[0]$($args[1]) 包含空格copy 命令会发生故障;因此,将文件名和+ 作为单独的 参数传递会更加稳健,copy 也支持:

      function join-file {
         # Pass the arguments individually, which obviates the need for quoting
         # and $(...) altogether:
         cmd /c copy /b $args[0] + $args[1] $args[2]
      }
      

      [1] 您可以按如下方式验证这一点:$arr='foo', 'bar'; cmd /c echo $($arr[0])+$($arr[1]),产生:foo +bar(注意空格)。

      【讨论】:

        猜你喜欢
        • 2012-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 1970-01-01
        • 1970-01-01
        • 2011-09-22
        • 2021-12-24
        相关资源
        最近更新 更多