首先是您的顺序错误,因为write-host
仅将内容输出到控制台窗口而没有发送任何内容到管道。
其次,UserPrincipalName
您使用的并不总是与用户完全相同PrimarySmtpAddress
(可能是,但并非总是如此)
我认为这会让你更进一步:
$getusrname = Read-Host "what is the user name?"
# instead of using a Filter, you can also experiment with the '-Anr' parameter
# to perform an ambiguous name resolution (ANR) search.
# See: https://docs.microsoft.com/en-us/powershell/module/exchange/mailboxes/get-mailbox?view=exchange-ps#parameters
$users = Get-Mailbox -Filter "Name -like '*$getusrname*'" |
Select-Object Name, @{Name = "Email adress"; Expression = 'PrimarySmtpAddress'}
if ($users) {
Write-Host "I found these user(s):"
$users | Format-Table -AutoSize
}
else {
Write-Host "No user found for $getusrname" -ForegroundColor Red
}