powershellwrite-host

How do I write-host a single property of an element in a powershell array?


I queried Office365 for a list of all users that match the displayName of Chris.

I'd like to prompt the user for which Chris they want to select. In doing so I have the following for..each code

$tmpUserOffice = Get-MsolUser -SearchString "*Chris*"
if ($tmpUserOffice -is [array])
{
    if ($tmpUserOffice.Count -lt 50) {
        Write-Host "Many matching users in MSOL. Choose which one you want to save"    
        for ($i = 0; $i -lt $tmpUserOffice.Count; $i++) {
            Write-Host $i " "  $($tmpUserOffice[$i].DisplayName) 
        }   
        Write-Host $tmpUserOffice.Count " None of the above" 
        $chosen = Read-Host

        if ($chosen -eq $tmpUserOffice.Count) {
            Write-Warning "Nothing found. Try searching with different criteria or use wildcards"
            Write-Output $null
        }

        Write-Host $tmpUserOffice[$chosen] " selected" 
        $tmpUserOffice = $tmpUserOffice[$chosen]
        exit
    }
    else {
        Write-Warning "More than 50 matches found. Try searching for more specific criteria"
    }
}

One of my problems is how to get the contents of the following line to complete

Write-Host $i " "  $($tmpUserOffice[$i].DisplayName) 

Currently the output is

Many matching users in MSOL. Choose which one you want to save 
0
1
2  None of the above

What changes do I need to make to ensure that this value actually writes a value?

Editor's note: The problem turned out to be unrelated to the code posted here, which does work in principle.


Solution

  • I think that you just need to enclose it in double quotes:

    Write-Host "$i  $($tmpUserOffice[$i].DisplayName)"
    

    The double quotes allow you to embed variables $i, and the $(...) allows the value to be evaluated before being displayed.