【问题标题】:Passing around command line $args in powershell , from function to function在 powershell 中传递命令行 $args,从函数到函数
【发布时间】:2010-11-21 04:40:05
【问题描述】:

这是我面临的一个令人讨厌的问题。如果它有一个简单的解决方案,我不会感到惊讶,只是它让我望而却步。

我有 2 个批处理文件,我必须将它们转换为 powershell 脚本。

file1.bat
---------

echo %1
echo %2
echo %3
file2.bat %*

file2.bat
--------
echo %1
echo %2
echo %3

在命令行中,我将其调用为 C:> file1.bat 一二三 我看到的输出符合预期 一 二 三 一 二 三

(这是一个粗略的代码示例)

当我转换为 Powershell 时,我有

file1.ps1
---------
Write-Host "args[0] " $args[0]
Write-Host "args[1] " $args[1]
Write-Host "args[2] " $args[2]
. ./file2.ps1 $args

file2.ps1
---------
Write-Host "args[0] " $args[0]
Write-Host "args[1] " $args[1]
Write-Host "args[2] " $args[2]

When I invoke this on powershell command line, I get
$> & file1.ps1 one two three
args[0] one
args[1] two
args[2] three
args[0] one two three 
args[1] 
args[2] 

我理解这是因为 file1.ps 中使用的 $args 是一个 System.Object[] 而不是 3 个字符串。

我需要一种将 file1.ps1 收到的 $args 传递给 file2.ps1 的方法,这与 .bat 文件中的 %* 实现的方法非常相似。

恐怕,即使是跨函数调用,现有的方式也会中断,就像我的示例中的跨文件调用一样。

尝试了几种组合,但没有任何效果。

请帮助。非常感谢。

【问题讨论】:

    标签: command-line powershell nested arguments


    【解决方案1】:

    PowerShell V2 中,飞溅是微不足道的。 bar 就变成了:

    function bar { foo @args }
    

    Splatting 会将数组成员视为单独的参数,而不是将其作为单个数组参数传递。

    PowerShell V1 中这很复杂,有一种方法可以处理位置参数。给定一个函数 foo:

    function foo { write-host args0 $args[0] args1 $args[1] args2 $args[2]   }
    

    现在使用 foo 函数的脚本块上的 Invoke() 方法从 bar 调用它

    function bar { $OFS=',';  "bar args: $args";  $function:foo.Invoke($args) }
    

    看起来像

    PS (STA) (16) > 小节 1 2 3 条形参数:1,2,3 参数0 1 参数1 2 参数2 3

    当你使用它时。

    【讨论】:

      【解决方案2】:
      # use the pipe, Luke!
      
      file1.ps1
      ---------
      $args | write-host
      $args | .\file2.ps1    
      
      file2.ps1
      ---------
      process { write-host $_ }
      

      【讨论】:

      • 你能解释一下这是做什么的吗?
      • 它打印传递给 file1.ps1 的参数,然后将这些参数传递给 file2.ps1 再次打印(以显示它们按预期到达)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多