简体   繁体   English

Powershell函数中的参数传递

[英]argument pass in powershell function

I am facing a problem to add loop count with a variable and than pass it to function and print details. 我面临的一个问题是添加带有变量的循环计数,然后将其传递给函数并打印详细信息。 please suggest your wise suggestion. 请提出您的明智建议。

My code is shown below: 我的代码如下所示:

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"
}

when i run this, it prints 当我运行它时,它会打印

1
1
2
2

but i want the output like: 但我想要这样的输出:

no report
no report
with report
with report

Thanks in advance. 提前致谢。

You have to actually invoke that expression, so the variable expands, and you have to escape $ with `, so it doesnt try to expand it 您必须实际调用该表达式,变量才能展开,并且必须使用`转义$ ,因此它不会尝试扩展它

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

Invoke-Expression: 调用表达:

The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Invoke-Expression cmdlet评估或运行指定的字符串作为命令,并返回表达式或命令的结果。 Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged. 如果没有Invoke-Expression,则在命令行提交的字符串将原样返回(回显)。

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

edit: another way to do that (probably better and safer) by Mathias 编辑:另一种方法来做到这一点(可能更好,更安全),作者是Mathias

$ExecutionContext.InvokeCommand.ExpandString("`$test_$i")

An alternative method that is a little more understandable is to use Get-Variable . 一种更容易理解的替代方法是使用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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM