如何将parameter passing给函数?

我需要在PS脚本中处理SVN工作副本,但是我无法将parameter passing给函数。 这是我有:

function foo($arg1, $arg2) { echo $arg1 echo $arg2.FullName } echo "0: $($args[0])" echo "1: $($args[1])" $items = get-childitem $args[1] $items | foreach-object -process {foo $args[0] $_} 

我想将$arg[0]作为$arg1传递给foo ,将$arg[1]作为$arg2传递。 然而,它不起作用,出于某种原因$arg1总是空的:

 PS C:\Users\sbi> .\test.ps1 blah .\Dropbox 0: blah 1: .\Dropbox C:\Users\sbi\Dropbox\Photos C:\Users\sbi\Dropbox\Public C:\Users\sbi\Dropbox\sbi PS C:\Users\sbi> 

注意: "blah"参数不作为$arg1传递。

我绝对相信这是一件简单的事情(我只是刚开始做PS,还觉得很笨拙),但是现在一个多小时的时间里,我已经把我的头撞到了这里,而我什么也找不到。

$arg[]数组似乎在ForEach对象内部失去了作用域。

 function foo($arg1, $arg2) { echo $arg1 echo $arg2.FullName } echo "0: $($args[0])" echo "1: $($args[1])" $zero = $args[0] $one = $args[1] $items = get-childitem $args[1] $items | foreach-object { echo "inner 0: $($zero)" echo "inner 1: $($one)" } 

$ args [0]没有在foreach对象中返回任何东西的原因是$ args是一个自动variables,它将一个未命名的,不匹配的parameter passing给一个命令,foreach对象是一个新的命令。 对于进程块没有任何不匹配的参数,所以$ args [0]为空。

有一件事可以帮助你的脚本可以有参数,就像函数一样。

 param ($SomeText, $SomePath) function foo($arg1, $arg2) { echo $arg1 echo $arg2.FullName } echo "0: $SomeText" echo "1: $SomePath" $items = get-childitem $SomePath $items | foreach-object -process {foo $SomeText $_} 

当你开始想从你的参数中获得更多的function的时候,你可能想看看我写的从$ args到我们现在可以使用的当前高级参数的博客文章。

尝试这样的事情:

 # Use an advanced function function foo { [CmdletBinding()] param ( [string] $arg1 , [string] $arg2 ) Write-Host -Object $arg1; Write-Host -Object $arg2; } # Create array of "args" to emulate passing them in from command line. $args = @('blah', 'c:\test'); echo "0: $($args[0])" echo "1: $($args[1])" # Force items to be returned as an array, in case there's only 1 item returned $items = @(Get-ChildItem -Path $args[1]); Write-Host -Object "There are $($items.Count) in `$items"; # Iterate over items found in directory foreach ($item in $items) { foo -Arg1 $args[0] -Arg2 $item.FullName }