Powershell script to indexof value from array

Viewed 96

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"
}
1 Answers

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.

Related