[英]argument pass in powershell function
我面临的一个问题是添加带有变量的循环计数,然后将其传递给函数并打印详细信息。 请提出您的明智建议。
我的代码如下所示:
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
提前致谢。
您必须实际调用该表达式,变量才能展开,并且必须使用`转义$
,因此它不会尝试扩展它
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")
一种更容易理解的替代方法是使用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.