Reputation: 17
I'm new to PS and I'm trying to find a user or group (Azure) based on user input $guid
. If a user is found, I would like for the script to not look for groups. My script is not working, and I'm unsure what mistake I am doing. I would gladly appreciate it if someone could point out what's wrong here and how to correct it. Thank you!
#Find user/group
$user = Get-AzADUser -ObjectId $guid
$group = $false
if ($user)
{
$user | FL Mail, MailNickName; break
}
else
{
Get-AzADGroup -ObjectId $guid | FL DisplayName, MailNickName
$group = $true
if ($group -eq $false)
{
Write-Warning "No matches found."
}
}
Upvotes: 1
Views: 369
Reputation: 61148
Why not simplify to something like this:
#Find user or group
$object = Get-AzADUser -ObjectId $guid
if (!$object) { $object = Get-AzADGroup -ObjectId $guid } # not a user; try group
if ($object) { $object | Select-Object DisplayName, MailNickName }
else { Write-Warning "No matches found." }
Upvotes: 0
Reputation: 761
A few recommendations:
$group = $true
as recommended by mklement0
Get-AzADGroup -ObjectId $guid | FL DisplayName, MailNickName
to $group = Get-AzADGroup -ObjectId $guid
$user | FL Mail, MailNickName; break
This is how your script should look like:
#Find user/group
$user = Get-AzADUser -ObjectId $guid
# it is better to initialize a variable with $null instead of $false
$group = $null
if ($user)
{
# also no need to "break" use if you are not using loop so I removed "break"
$user | FL Mail, MailNickName
}
else
{
$group = Get-AzADGroup -ObjectId $guid
if ($group -eq $false)
{
Write-Warning "No matches found."
}
else {
$group | FL DisplayName, MailNickName
}
}
Just to make your script smaller:
#Find user/group
$user = $null
$group = $null
$user = Get-AzADUser -ObjectId $guid
$group = Get-AzADGroup -ObjectId $guid
if ($user)
{
$user | FL Mail, MailNickName
}
if ($group)
{
$group | FL DisplayName, MailNickName
}
Upvotes: 2