The below command will print out a list of string
Invoke-Expression -Command "mc.exe admin policy list $target" -OutVariable policiesList | Out-Null
In the powershell script, there is a prompt to enter some value
$option = Read-Host -Prompt "Enter option: "
I wanted to keep prompting the "Read-Host" to capture user value until the value (in $option ) matches in the policiesList. I have tried using the IndexOf, but it returns -1 even though the $option matches one of the value in policiesList
$rr=[array]::IndexOf($policiesList , $option)
echo $rr
The below is my entire script
Invoke-Expression -Command "mc.exe admin policy list $target" -OutVariable policiesList | Out-Null
$option=""
$i=[Array]::IndexOf($policiesList, $option)
while($i -eq -1){
$i=[Array]::IndexOf($policiesList, $option)
$option = Read-Host -Prompt "Enter option"
}
CodePudding user response:
Note: Invoke-Expression
(iex
) should generally be avoided; definitely don't use it to invoke an external program or PowerShell script.
Therefore, reformulate your call to mc.exe
as follows:
# Saves the output lines as an array in $policies.
$policies = mc.exe admin policy list $target
Note that [Array]::IndexOf()
uses case-sensitive lookups, which may be why the lookups don't succeed.
A case-insensitive approach that is also simpler is to use PowerShell's -in
operator. (Note that the comparison value must match an array element in full either way.)
do {
$option = Read-Host -Prompt "Enter option"
} while ($option -notin $policies)
CodePudding user response:
Try casting the result of Invoke-Expression to an array, as Invoke-Expression returns a PSObject type.
$policiesList = @(Invoke-Expression -Command "mc.exe admin policy list $target")
$option=""
$i=[Array]::IndexOf($policiesList, $option)
while($i -eq -1){
$i=[Array]::IndexOf($policiesList, $option)
$option = Read-Host -Prompt "Enter option"
}