如何在 powershell 数组中写入托管元素的单个属性?

Ran*_*Dom 3 powershell write-host

我查询 Office365 以获取与Chris的 displayName 匹配的所有用户的列表。

我想提示用户他们想要选择哪个克里斯。这样做时,我有以下 for..each 代码

$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"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题之一是如何让以下行的内容完成

Write-Host $i " "  $($tmpUserOffice[$i].DisplayName) 
Run Code Online (Sandbox Code Playgroud)

目前的输出是

Many matching users in MSOL. Choose which one you want to save 
0
1
2  None of the above
Run Code Online (Sandbox Code Playgroud)

我需要进行哪些更改才能确保该值实际写入一个值?

编者注:该问题与此处发布的代码无关,原则上确实有效。

HAL*_*256 5

我认为你只需要把它用双引号引起来:

Write-Host "$i  $($tmpUserOffice[$i].DisplayName)"
Run Code Online (Sandbox Code Playgroud)

双引号允许您嵌入变量$i,并且$(...)允许在显示之前对值进行评估。

  • 如果这有效,那么OP自己的尝试也有效。虽然一般来说使用单个可扩展字符串可能有优势,但在这里没有什么区别(而且我们已经了解到OP的问题与他们使用“Write-Host”无关)。顺便说一句:要使用可扩展字符串完全模拟 `Write-Host $i " " $($tmpUserOffice[$i].DisplayName)`,您需要在 `$i` 和 `$(...)` 之间添加 _3_ 空格- 尽管由于对参数处理方式的误解,OP可能只意味着有_1_。 (2认同)