我面临着一个问题,如何使用变量添加循环计数,然后将其传递给函数并打印详细信息。请提出你的明智的建议。
我的代码如下所示:
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提前谢谢。
发布于 2017-03-01 21:48:00
您必须实际调用该表达式,因此变量会展开,并且您必须使用`转义$,所以它不会尝试展开它
CheckErrorMessage 'plugin-1' $(iex "`$test_$i")Invoke-Expression:
Invoke-Expression cmdlet将指定的字符串作为命令进行计算或运行,并返回表达式或命令的结果。如果没有Invoke-Expression,在命令行提交的字符串将原封不动地返回(回显)。
编辑: Mathias的另一种方法(可能更好更安全)
$ExecutionContext.InvokeCommand.ExpandString("`$test_$i")发布于 2017-03-02 00:06:15
另一种更容易理解的方法是使用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
}https://stackoverflow.com/questions/42533308
复制相似问题