0

so I'am writing a script to automate connection to o365 and exchange online, i was able to do that, then the script spouse to show me specific properties and from some reason it's selection only one property

$getusrname = read-host "what is the user name?"

Get-Mailbox -Identity *$getusrname* | ForEach-Object { write-host -ForegroundColor White "I found these users: $_"} | select name, @{n="Email adress";e='UserPrincipalName'}

I'am getting this output:

 I found these users: Lev Leiderman

Thanks for your help

WebsGhost
  • 107
  • 1
  • 14

1 Answers1

0

First thing is that you have the order wrong, since write-host only outputs stuff to the console window and sends nothing through to the pipe.

Secondly, the UserPrincipalName you use is not always exactly the same as the users PrimarySmtpAddress (could be, but not always the case)

I think this would get you further:

$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://learn.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
}
Theo
  • 57,719
  • 8
  • 24
  • 41
  • Thanks a lot for your help, it's indeed working but it's too much lines for such "poor task" may you tell me what is the difference between "-filter" and "-identity" ? – WebsGhost Oct 31 '19 at 12:06
  • @WebsGhost Too many lines? It is a bad thing to try and slam everything in one-liners because as you noticed, with those it is very easy to make mistakes and hard to detect them. `-Filter` can use wildcard characters like `*`. For `-Identity` you need to exactly specify the mailbox. See [Get-Mailbox](https://learn.microsoft.com/en-us/powershell/module/exchange/mailboxes/get-mailbox?view=exchange-ps#parameters) – Theo Oct 31 '19 at 12:32
  • I have to admit, there is a point.. i've tried the `-anr` and it' didn't worked by the way. – WebsGhost Oct 31 '19 at 12:34
  • @WebsGhost With `-Anr` you cannot use the wildcard `*` characters. Have you looked at the official documentation I have linked to? – Theo Oct 31 '19 at 12:36
  • Yes my friend i had some spelling mistakes :) thanks ! – WebsGhost Oct 31 '19 at 13:38
  • @WebsGhost Great, glad to have helped. – Theo Oct 31 '19 at 13:42