参数传递给powershell函数

时间:2017-03-01 13:39:49

标签: powershell powershell-v5.0

我面临一个问题,即使用变量添加循环计数,然后将其传递给函数和打印详细信息。请提出你明智的建议。

我的代码如下所示:

function CheckErrorMessage {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNullOrEmpty()]
        $Plugin

      , [Parameter(Mandatory = $true, Position = 1)]
        [ValidateNotNullOrEmpty()]
        $Report_Decission       
)

switch ($Plugin){

    'plugin-1' {

        $Report_Decission  

    }

    'plugin-2' {

       $Report_Decission  
    }

    Default {

   }
}
}#functions ends here

$test_1 = "no report"
$test_2 = "with report"

for($i=1; $i -ne 3; $i++){

CheckErrorMessage 'plugin-1' "$test_$i"  # i want to sent $test_1 or $test_2 from here
CheckErrorMessage 'plugin-2' "$test_$i"
}

当我运行它时,它打印

1
1
2
2

但我希望输出如下:

no report
no report
with report
with report

提前致谢。

2 个答案:

答案 0 :(得分:2)

你必须实际调用该表达式,因此变量会扩展,你必须用`转义$,所以它不会尝试扩展它

CheckErrorMessage 'plugin-1' $(iex "`$test_$i")

调用-表达式:

Invoke-Expression cmdlet将指定的字符串作为命令计算或运行,并返回表达式或命令的结果。如果没有Invoke-Expression,在命令行提交的字符串将返回(回显)不变。

参考:https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/invoke-expression

编辑:Mathias

的另一种方式(可能更好,更安全)
$ExecutionContext.InvokeCommand.ExpandString("`$test_$i")

答案 1 :(得分:1)

更易理解的另一种方法是使用Get-Variable

...
$test_1 = "no report"
$test_2 = "with report"

for($i=1; $i -ne 3; $i++) {
  CheckErrorMessage 'plugin-1' (Get-Variable "test_$i").Value
  CheckErrorMessage 'plugin-2' (Get-Variable "test_$i").Value
}
相关问题