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. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.
edit: another way to do that (probably better and safer) by Mathias
$ExecutionContext.InvokeCommand.ExpandString("`$test_$i")
An alternative method that is a little more understandable is to use 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.