powershell 函数中的参数传递
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 评估或运行指定的字符串作为命令,returns 表达式或命令的结果。如果没有 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
}
我在使用变量添加循环计数并将其传递给函数并打印详细信息时遇到问题。请提出您的明智建议。
我的代码如下所示:
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 评估或运行指定的字符串作为命令,returns 表达式或命令的结果。如果没有 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
}