powershelloffice365

Microsoft Graph User Creation


I'm scripting a new version of a script I've done before, but I'm upgrading it to use MSGraph for Office 365 account creation.

I'm running across an issue here, since I created a function to test if a user exists:

#Function to check account existence
Function AccountExists
{
    Param(
            [string]$fxEmailAccount
          )
    
    #Validamos si la cuenta existe
    $return = [System.Convert]::ToBoolean("TRUE")
    try {
        $user = Get-MgUser -UserId $fxEmailAccount
        Write-Output $($user.Count())
    }
    catch {
            $return = [System.Convert]::ToBoolean("FALSE")
    }
    return $return
}

$result = AccountExists -fxEmailAccount zpinillal@mydomain.com

Partially this works for me, the issue here is how can I properly check for the existence of an account, since Get-MGUser returns an object and every time I run my function, it sometimes fail because of my implemented logic.

I already tried to use Get-MgUserCount, but didnt' got any luck on this approach either.

Can someone tell me what might I'm doing wrong or not interpreting well to do this.

Thanks,


Solution

  • Your function can probably be reduced to the following, PowerShell-idiomatic form:

    function Test-AccountExists {
      param(
        $UserId
      )
      [bool] (Get-MgUser -UserId $UserId -ErrorAction Ignore)
    }
    
    # Sample invocation
    $result = Test-AccountExists -UserId zpinillal@mydomain.com
    

    As for what you tried: