Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with retrieving data from Graph API to PowerShell

I’m starting to work with PowerShell scripts and I’m having an issue with user.accountEnabled. I found out that I need to use the appropriate select statement when retrieving data, so I’m using

https://graph.microsoft.com/v1.0/users/?$select=displayname,accountEnabled,userPrincipalName

I’m using the app ID and app secret, and I confirmed in Postman (using the same credentials) that I’m getting correct responses without any permission issues, and everything looks fine.

My problem is that when I assign the accountEnabled data to a variable, no value is added.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Below is the script with sensitive data censored.

function Get-ListOfExchangeUsers {
    # Dane do połączenia z bazą danych
    $ServerName = "x"
    $DatabaseName = "pwa"

    # Połączenie z bazą danych
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server=$ServerName;Database=$DatabaseName;Integrated Security=True"
    $SqlConnection.Open()

    $TenantId = "x"
    # Identyfikator aplikacji
    $AppId = "x"
    # Tajny klucz aplikacji
    $AppSecret = "x"

    # Utwórz adres URL żądania tokena
    $authUrl = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"

    # Utwórz obiekt żądania tokenu
    $tokenRequestBody = @{
        grant_type    = "client_credentials"
        client_id     = $AppId
        client_secret = $AppSecret
        scope         = "https://graph.microsoft.com/.default"
    }

    # Wyślij żądanie tokenu do usługi Azure AD
    $tokenResponse = Invoke-RestMethod -Method POST -Uri $authUrl -Body $tokenRequestBody

    # Pobierz token dostępu z odpowiedzi
    $accessToken = $tokenResponse.access_token

    # Utwórz nagłówek autoryzacji z tokenem dostępu
    $authHeader = @{
        "Authorization" = "Bearer $accessToken"
        "Content-Type"  = "application/json"
    }

    # Wykonaj żądanie API Microsoft Graph w celu pobrania użytkowników
    $graphUrl = "https://graph.microsoft.com/v1.0/users/?$select=displayname,accountEnabled,userPrincipalName"
    $Users = Invoke-RestMethod -Method GET -Uri $graphUrl -Headers $authHeader

    # Dodaj pobrane dane użytkowników do tabeli "allmailboxes" w bazie danych "pwa"
    foreach ($user in $Users.value) {
        $email = $user.userPrincipalName
        
        # Zapytanie SQL sprawdzające, czy istnieje już użytkownik o podanym adresie email w tabeli allmailboxes
        $query = "SELECT * FROM allmailboxes WHERE EmailAddress = '$email'"
        
        $command = New-Object System.Data.SqlClient.SqlCommand($query, $SqlConnection)
        $result = $command.ExecuteScalar()
        
        # Jeśli zapytanie zwróciło wynik, to znaczy że taki użytkownik już istnieje w bazie danych - pomiń go
        if ($null -ne $result) {
            # Sprawdź, czy konto użytkownika jest wyłączone
         
            $accountEnabled = $user.accountEnabled
           
            Write-Host $email
            Write-Host $accountEnabled

            if ($accountEnabled -eq $false) {
                $query = "UPDATE allmailboxes SET Disabled = 'true' WHERE EmailAddress = '$email'"
                $command = New-Object System.Data.SqlClient.SqlCommand($query, $SqlConnection)
                $command.ExecuteNonQuery()
                continue
            }
            continue
        }

        # Pobierz informację o tym, czy konto jest wyłączone czy włączone
        $disabled = $user.accountEnabled
        
        # Jeśli taki użytkownik nie istnieje w bazie danych, dodaj go do tabeli allmailboxes
        $fullName = $user.displayName
        $query = "INSERT INTO allmailboxes (FullName, EmailAddress, Disabled) VALUES ('$fullName', '$email', '$disabled')"
        $command = New-Object System.Data.SqlClient.SqlCommand($query, $SqlConnection)
        $command.ExecuteNonQuery()
    }

    # Zamknij połączenie z bazą danych
    $SqlConnection.Close()

    # Zwróć listę użytkowników
    return $Users
}

I added a line to the script to display the values of accountEnabled, and it shows a null value.

Powershell

The last account on the list is disabled and should return a different value than the others. I am also attaching the response from Graph API.

API

Could someone take a look at this and verify what I am doing wrong?

>Solution :

The address you want to call is

https://graph.microsoft.com/v1.0/users/?$select=displayname,accountEnabled,userPrincipalName

Right now, because it is all in double-quotes and there is no $select variable anywhere, your url gets down to this

https://graph.microsoft.com/v1.0/users/?=displayname,accountEnabled,userPrincipalName

If you declare your url in single-quotes, it should work fine, so:

$graphUrl = 'https://graph.microsoft.com/v1.0/users/?$select=displayname,accountEnabled,userPrincipalName'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading