1

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"
}
xxestter
  • 441
  • 7
  • 19
  • 2
    Why not just use $policiesList = Invoke-Expression -Command "mc.exe admin policy list $target" - that'd save having to use Out-Null Also, what is the type of $policiesList? Use $policiesList.GetType() to find out as very often a data type that would appear to be an array is not an array. – endurium Jul 13 '22 at 10:58

1 Answers1

1

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 -inoperator. (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) 

Note that -in returns $true or $false, i.e. whether the element was found in the collection, not the index at which the element was found.

However, in your case this is sufficient.

In cases where you do need to know the index in combination with case-insensitive lookups, you can use [Array]::FindIndex(), as shown in this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775