P Wang
P Wang

Reputation: 17

Nested If statement Powershell

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

Answers (2)

Theo
Theo

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

LT-
LT-

Reputation: 761

A few recommendations:

  • Remove $group = $true as recommended by mklement0
  • Also Change this line from Get-AzADGroup -ObjectId $guid | FL DisplayName, MailNickName to $group = Get-AzADGroup -ObjectId $guid
  • Remove break from the following line, it's only required in loops $user | FL Mail, MailNickName; break
  • Use $null to initialize variables instead of $false

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

Related Questions