r/GraphAPI • • Aug 06 '24

Manage Microsoft Entra objects with Micro Graph Powershell

2 Upvotes

Hello all,

First, I would like to let you all know that I am using Microsoft Graph Powershell for the first time to test out this documentation https://learn.microsoft.com/en-us/training/modules/manage-azure-active-directory-identities/5-manage-azure-active-directory-objects-powershell .

I was able to login to my account using a global administrator account.

After running this powershell script:

$users = Import-Csv -Path "C:\path\to\your\Users.csv"

foreach ($user in $users) {

New-MgUser -UserPrincipalName $user.UserName `

-GivenName $user.FirstName `

-Surname $user.LastName `

-DisplayName $user.DisplayName `

-JobTitle $user.JobTitle `

-Department $user.Department `

-AccountEnabled $true `

-MailNickname $user.FirstName `

-UsageLocation "US" `

-PasswordProfile @{ForceChangePasswordNextSignIn = $true; Password = "Password"}

}

I keep on getting an error message stating that I don't have permissions. I am using a Global admin account to no avail.

Please help!!

Thanks,


r/GraphAPI • • Jan 24 '25

Help with Microsoft Graph API: Unable to Access hardwarePasswordInfo Using Enterprise Application Token

Thumbnail reddit.com
1 Upvotes

r/GraphAPI • • Oct 16 '24

Cannot Give App Registration Access to Sharepoint-Site

1 Upvotes

Hello Everyone

I am trying to set up an App-Registration that should have write permissions to a specific site. Unfortunately I still get the error that I do not have the needed permissions, even though the App has the permissions "Site.Selected" and temporarily "Sites.FullControl"

This is the script I am using

# Define the Application (Client) ID and Secret

$ApplicationClientId = <clientID> # Application (Client) ID

$ApplicationClientSecret = <secret> # Application Secret Value

$TenantId = <tenantID> # Tenant ID

# Convert the Client Secret to a Secure String

$SecureClientSecret = ConvertTo-SecureString -String $ApplicationClientSecret -AsPlainText -Force

# Create a PSCredential Object Using the Client ID and Secure Client Secret

$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationClientId, $SecureClientSecret

# Connect to Microsoft Graph Using the Tenant ID and Client Secret Credential

Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $ClientSecretCredential

#Name of the site

$siteName = "DCMPartners"

 

# The App Registration that needs access

$appId = <appID>

$appName = <AppName>

 

# This is the geo specific name

# Example, for , this would be contosogbr.

$spoTenantName = <TenantName>

 

# In the case of this Graph snippet I am doing a single site. But one can extend this to loop over multiple sites if needed. 

 

# Get the site Id of the site. This is what Graph uses to refer to SharePoint sites.

$siteId = ((Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/sites/$spoTenantName.sharepoint.com:/sites/$siteName/").id -split ',')[1]

 

# Define the paramters for the cmdlet

$mgSiteParams = [ordered]@{

    "roles" = @("write")

    "grantedToIdentities" = @(

        @{

            "application" = @{

                "id" = $appId

                "displayName" = $appName

            }

        }

    )

}

#I tried this one

# Assign the permissions

New

 

# And this one

Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/sites/$siteId/permissions" `

                    -Method 'POST' -ContentType "application/json" `

                    -Body (ConvertTo-Json -Depth 5 $mgSiteParams)https://contosogbr.sharepoint.com/xxx

This is the error message im getting:

Invoke-MgGraphRequest : GET https://graph.microsoft.com/v1.0/sites/wingd.sharepoint.com:/sites/DCMPartners/
HTTP/1.1 403 Forbidden
Transfer-Encoding: chunked
Vary: Accept-Encoding
Strict-Transport-Security: max-age=31536000
request-id: c1a52d37-89e7-4363-a897-3b255f3028cb
client-request-id: a34b70c5-27c1-44b1-80f0-174402e12b72
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"Switzerland North","Slice":"E","Ring":"3","ScaleUnit":"001","RoleInstance":"ZRH2EPF000000E2"}}
Cache-Control: no-store, no-cache
Date: Wed, 16 Oct 2024 10:12:03 GMT
Content-Encoding: gzip
Content-Type: application/json
{"error":{"code":"accessDenied","message":"Access denied","innerError":{"date":"2024-10-16T10:12:03","request-id":"c1a52d37-89e7-4363-a897-3b255f3028cb","client-request-id":"a34b70c5-27c1-44b1-80f0-174402e12b72"}}}
At line:15 char:13

  • $siteId = ((Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v ...

  • \~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~

  • CategoryInfo : InvalidOperation: (Method: GET, Re...174402e12b72 }:HttpRequestMessage) [Invoke-MgGraphRequest], HttpResponseException

  • FullyQualifiedErrorId : InvokeGraphHttpResponseException,Microsoft.Graph.PowerShell.Authentication.Cmdlets.InvokeMgGraphRequest Invoke-MgGraphRequest : POST https://graph.microsoft.com/v1.0/sites/e442d28d-cb72-4924-b6c4-6bfbb3491063/permissions HTTP/1.1 403 Forbidden Transfer-Encoding: chunked Vary: Accept-Encoding Strict-Transport-Security: max-age=31536000 request-id: 39f1199f-0c78-489b-93a1-235bf37470dd client-request-id: b6312e11-164b-4081-b0f6-d7595bf6999f x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"Switzerland North","Slice":"E","Ring":"3","ScaleUnit":"001","RoleInstance":"ZRH2EPF000000DF"}} Link: https://developer.microsoft-tst.com/en-us/graph/changes?$filterby=v1.0,Removal&from=2021-09-01&to=2021-10-01;rel="deprecation";type="text/html", https://developer.microsoft-tst.com/en-us/graph/changes?$filterby=v1.0,Removal&from=2021-09-01&to=2021-10-01;rel="deprecation";type="text/html" Deprecation: Fri, 03 Sep 2021 23:59:59 GMT Sunset: Sun, 01 Oct 2023 23:59:59 GMT Cache-Control: no-store, no-cache Date: Wed, 16 Oct 2024 10:12:02 GMT Content-Encoding: gzip Content-Type: application/json {"error":{"code":"accessDenied","message":"Access denied","innerError":{"date":"2024-10-16T10:12:03","request-id":"39f1199f-0c78-489b-93a1-235bf37470dd","client-request-id":"b6312e11-164b-4081-b0f6-d7595bf6999f"}}} At line:31 char:1

  • Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/sites/$s ...

  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • CategoryInfo : InvalidOperation: (Method: POST, R...ication/json }:HttpRequestMessage) [Invoke-MgGraphRequest], HttpResponseException

  • FullyQualifiedErrorId : InvokeGraphHttpResponseException,Microsoft.Graph.PowerShell.Authentication.Cmdlets.InvokeMgGraphRequest Any Idea what I might have missed?

Thank you for your help.

Cheers,

Gabe


r/GraphAPI • • Oct 03 '24

Exchange 365 users with additional access/permission

1 Upvotes

Hi,
is there a way to get the users with access permissions on other mailboxes other than their own using REST API?

Some IT members gave access to users to other users' mailboxes. Since I have thousands of mailboxes to check, I would prefer an audit via API REST.

Thank you.


r/GraphAPI • • Apr 30 '24

Graph API - Deleting not working with username/password auth

1 Upvotes

Would love some help from any experts on this. I'm attempting to build a simple service that pulls emails from an Office 365 email box using the Microsoft Graph API. The service finds all new email, processes them using internal business logic, then deletes them from the box. Very standard service.

I've tried using both Application and Delegated authority and can't get it working either way. I can read the email, but deleting or moving it fails.

Dim graphClient As GraphServiceClient = Nothing
Dim scopes = {"Mail.ReadWrite"}
Dim options = New UsernamePasswordCredentialOptions With {.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud}
Dim userNamePasswordCredential = New UsernamePasswordCredential(username:=username, password:=password, tenantId:=tenantId, clientId:=applicationId, options:=options)
graphClient = New GraphServiceClient(userNamePasswordCredential, scopes)

... Pull Emails... Now delete them:

Dim userReqHelper = graphClient.Me.Messages(messageId)
Await userReqHelper.DeleteAsync()

This throws an exception of "Content type text/html does not have a factory registered to be parsed"

I've tried deleting it with userReqHelper = graphClient.Users(userId).Messages(messageId).DeleteAsync() and userReqHelper = graphClient.Me.MailFolders(sourceFolder).Messages(messageId).DeleteAsync() with the same problem. I tried switching to using application client/secret authentication, but apparently delete doesn't support that. I tried interactive and it doesn't seem to work either, some kind of problem with the scope.

Application is registered with the tenant in Entra as an enterprise application with permissions and grants:

I also enabled public client flows since some research showed that might help.

Any suggestions appreciated!


r/GraphAPI • • Dec 18 '23

Flagging emails automatically using Graph.

2 Upvotes

Hello everyone, I appreciate all help that can be given.

Part of our teams responsibilities is handling emergency meeting. I already have flows that can:

  • notify the team of incoming meetings.

  • gather details from the invite and catalogue them in a spreadsheet

  • assign these meetings to users in the spreadsheet, marking them as the facilitator

  • create reports of active meetings so management and others can follow along until the issue has been resolved.

Management also requires us to flag these emails with outer names. This is where I need help. I have experimented with the Graph API and I know I can flag an email, but I can only get it to flag with the generic message saying 'Follow up'.

How can I use Graph to flag the email with a custom value? I am sending the http request via power automate. This well be included in the flow that assigns users, so I will be able to use O365 lookup to get their name. I just need to be able to flag the email with their name.

Thank you in advance for any help you can provide.


r/GraphAPI • • Jan 11 '24

Can I start a content search with GraphAPI?

2 Upvotes

Hi,

I want to start a Content search using the Graph API just like I can using the Powershell. I want to basically do the following:

  Connect-IPPSSession

  New-ComplianceSearch -Name $SearchName -ExchangeLocation All -ContentMatchQuery $Filter

  New-ComplianceSearchAction -SearchName $SearchName -Purge -PurgeType SoftDelete -Confirm:$false -Force

Is it possible to do this yet?


r/GraphAPI • • Oct 04 '24

Get free/busy of external shared calendar

1 Upvotes

Hi, An external user, either a different workplace or private, i.e. outlook.com etc) shared their calendar free/busy with me. I'm currently struggling with 2 things:

  1. Is there a way to accept the invite using the graph API?

  2. Once accepted, how can I see their free/busy status?

For point 1, I think I can look at my messages in the API, but how can I get alerted that I got an invite message?

For number 2, I used the getSchedule endpoint but I get error messages 5009 that the user couldn't be found in active directory, which is correct because they're external to my org.

I'm new to using graph API so any help would be really appreciated 😊


r/GraphAPI • • Jan 30 '25

Read Calendars not working

1 Upvotes

I have granted myself calendars.read and calendars.readbasic but when I attempt to run in powershell get-mgbetausercalendarview it returns access is denied. According to this link Get calendar - Microsoft Graph v1.0 | Microsoft Learn the two of the permissions I've granted should be enough?

Any ideas what other permissions may be needed to pull this data?


r/GraphAPI • • Jul 24 '24

Generate Script in mggraph with Ad account authentication

1 Upvotes

Hello,

I am little bit new on developing in MGGRAPH. I have to develop a script for key management of app registration and keeping the same Key Id, this feature is only possible with MgGraph.

I tried with Az library and was not able to keep the same Key ID.

In MgGraph i was able to delete the old Secret and generate a new one and specify the Key ID.

The problem i am facing i want to automatise this process with CyberArk CPM platform and use connect-mggraph with an active Directory service account but i dont find user authentication for mggraph.

I am already aware of the existence of a CyberArk platform is for Key management but the key management require global admin or application admin right and in a security point of view is not a good practice. If an user rename the app id with another app id they can be able to reset the secret of other assets.

If we segregate with specific service account we can put as owner of the app registration the service account and manage only the Secret of the app registration were this service account is owner. Without exposing all our app registration secret.


r/GraphAPI • • Jan 22 '25

Can you create a planner task with markdown in the description?

2 Upvotes

This is driving me kind of nuts - I can edit a planner task which has no markdown in the Teams client or web client format it with markdown. If I edit a URL it'll become a hyperlink and become clickable, if I enclose a word with ** it'll work, etc.

When I query that event via the API I then see the markdown updates I made. I've verified that the event preview mode is set to 'description.' When I edit add markdown manually this is unchanged, and the markdown renders as expected.

However, when I create events with Markdown in the notes/description, I only see the literal text of the Markdown from teams and the teams client.

Is there something I'm missing? Has anyone been able to use markdown via graph, regardless of the client? I'm using Java, but I just want to know it's possible, be it powershell, c#, javascript, whatever. I'm just trying to gauge if I'm working toward something that's actually possible.


r/GraphAPI • • May 15 '24

Get Sign-In's with multiple failed MFA attempts

1 Upvotes

I want to use an Azure automation to block accounts that have multiple denied MFA attempts automatically. Number matching should prevent MFA fatigue attacks, but I would also like to block the account so I can change the user's password and revoke all sessions.

This is what the sign in looks like for testing:

How do I go about this?


r/GraphAPI • • Jan 06 '24

web based program for user to reset other user's email password

1 Upvotes

Is it possible to reset user passwords through web based program and graph? Or, is there a better way? I have a personal account that I use to maintain multiple domain names with a mix of a few hundred exchange/365 mailboxes. I would like to assign a different admin to each domain name so that the admin can (only) reset passwords for email accounts under their domain. Is this possible?


r/GraphAPI • • Aug 12 '23

Filter with "eq" operator is returning partial matches - how to get exact matches only?

1 Upvotes

My goal is to get a list of devices assigned to a user in Intune. I'm currently using the /deviceManagement/managedDevices with a filter based on the emailAddress of the user:

/deviceManagement/managedDevices?$filter=emailAddress eq '[email protected]'

but while this call succeeds, it also returns results for users that contain that same email string, for example [email protected]

I only want results for exact matches of the email address, is that possible?


r/GraphAPI • • Jul 05 '23

Getting a full Graph collection into Postman

2 Upvotes

Hello, I already have the postman collection for Microsoft Graph forked and working (https://www.postman.com/microsoftgraph/workspace/microsoft-graph/collection/455214-085f7047-1bec-4570-9ed0-3a7253be148c/fork)

All of the requests are working as intended, but I'm noticing that even though there's quite a bit, there isn't much in terms of Security requests. For instance, I want to bulk dismiss Risk Users. So at first I just thought Microsoft didn't have a request for that. But then I found this - https://learn.microsoft.com/en-us/graph/api/riskyuser-dismiss?view=graph-rest-1.0&tabs=http

So I made a custom request with it, and it worked in Postman. So the official postman collection for microsoft graph seems to have about 1% of what is really possible in Graph.

I guess what I think my question is... how can I get everything in here (https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) into Postman?

Thank you!


r/GraphAPI • • May 01 '24

How would I do this (can it be done this way?)

1 Upvotes

I am 100% new to graph, and have hardly ever used PowerShell, but I have been tasked with getting a list of all the apps for enterprise from azure AD (or entra, whatever the hell MS is calling now), from this list, I need to parse out the created date, and who created it. is there a simple (relatively) script to do this, or will this turn into a larger project?

I was able to get a list using graph explorer, so if worse comes to worse I could probably make a script to search that info from a text file, and compile it into a csv using maybe python or JavaScript? (I'm not a programmer by trade, I took some programming classes 7 years ago, but have been on the hardware side after that, until now. so my skills are small, and rusty.)

any help is greatly appreciated. Also if this is the wrong sub, please kindly point me in the direction of the correct one.


r/GraphAPI • • Oct 24 '24

Request an access token Get access on behalf of for Microsoft Graph

1 Upvotes

I am trying to test a simple token Get access on behalf of user with asp.net MVC using graph. I have created the site and when I launch the application I get an error:
TypeLoadException: Could not load type 'Microsoft.Graph.IAuthenticationProviderOption' from assembly 'Microsoft.Graph.Core, Version=3.1.22.0, Culture=neutral, PublicKeyToken=

I am wanting to use Graph 5.61. Are there any good tutorials on how to do this? I am wanting to get user attrbutes, Teams info, ToDo's etc...


r/GraphAPI • • Aug 09 '23

Open, edit, save, delete MS Office from my application

1 Upvotes

Hey Folks, I am building a java application which should be able to perform user actions on Ms Word stored on sharepoint on cloud.

I am having trouble with SSL when trying to call the necessary MS graph API.

Anyone has a solution for this?


r/GraphAPI • • Sep 24 '24

Outlook Graph API to get the next 5 events from this moment

1 Upvotes

Hi!
I am creating an app that will show the next 5 events from my outlook calendar. My current graph url kind of works, but the timestamp needs to be adjusted manually which I would like to have run automatically.

https://graph.microsoft.com/v1.0/users/myuser/events?$select=subject,start,end,location&$filter=start/dateTime ge '2024-09-06T07:29:45Z'&$top=5&$orderby=start/dateTime asc

I cannot find a way to have that filter work with a "time now" function.
I also tried to just not use a filter and transform the output with a subsequent script, but it only outputs 10 entries starting from 2016...

Not sure if anyone could shove me in the right direction?


r/GraphAPI • • Aug 26 '23

I put together a function to assist in making Filters for Graph queries. Figured I'd share :)

4 Upvotes

Was struggling with some Filtering with Graph and had an idea, and came up with this function to be a Filter builder for Graph queries.

# Function for assisting in making filters for Graph queries. 
function Generate-GraphFilter {
    param (
        [Parameter(Mandatory = $true)]
        [string]$Field,

        [Parameter(Mandatory = $true)]
        [ValidateSet('eq', 'ne', 'startsWith', 'endsWith', 'contains', 'le', 'ge', 'in', 'not')]
        [string]$Operator,

        [Parameter(Mandatory = $true)]
        [string]$Value,

        [switch]$Collection
    )

    $lambdaVar = "i" # or any other variable name you prefer

    switch ($Operator) {
        'eq' { $opString = "$Field eq '$Value'" }
        'ne' { $opString = "$Field ne '$Value'" }
        'startsWith' { $opString = "startswith($Field, '$Value')" }
        'endsWith' { $opString = "endswith($Field, '$Value')" }
        'contains' { $opString = "contains($Field, '$Value')" }
        'le' { $opString = "$Field le '$Value'" }
        'ge' { $opString = "$Field ge '$Value'" }
        'in' { 
            $valuesList = $Value -split ',' | ForEach-Object { "'$_'" } -join ','
            $opString = "$Field in ($valuesList)"
        }
        'not' { $opString = "not($Field eq '$Value')" } # Simplifying just for 'eq'; you can expand for other conditions
    }

    if ($Collection) {
        $opString = "$Field/any(${lambdaVar}:$opString)"
    }

    return $opString
}

# Sample Usage
$filterQuery = Generate-GraphFilter -Field "displayName" -Operator "startsWith" -Value "Doug"
Get-MgUser -Filter $filterQuery

r/GraphAPI • • Feb 13 '24

Defender Threat Email Submission API

1 Upvotes

r/GraphAPI • • Jan 10 '25

I am trying to get devices with a certain version of Teams using Powershell

1 Upvotes

I am trying to get devices with a certain version of Teams using Powershell. I am getting the following error when I run the attached code. Would anyone be able to help me see what's wrong with the code?

ERROR
Get-MgDeviceManagementManagedDeviceAppInventory : The term 'Get-MgDeviceManagementManagedDeviceAppInventory' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:20 char:22 + ... stalledApps = Get-MgDeviceManagementManagedDeviceAppInventory -Manage ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Get-MgDeviceMan...iceAppInventory:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

CODE

# Import the required modules
import-module Microsoft.Graph.Identity.Signins
Import-Module Microsoft.Graph.DeviceManagement
Import-Module ImportExcel

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Device.Read.All", "DeviceLocalCredential.ReadBasic.All" -NoWelcome

# Define the application name to search for
$appName = "Microsoft Teams Classic"

# Get all managed devices
$devices = Get-MgDeviceManagementManagedDevice -All

# Initialize a list for devices with the specified app
$devicesWithApp = @()

foreach ($device in $devices) {
    # Get installed applications on the device
    $installedApps = Get-MgDeviceManagementManagedDeviceAppInventory -ManagedDeviceId $device.Id -ErrorAction SilentlyContinue

    if ($installedApps) {
        foreach ($app in $installedApps) {
            if ($app.DisplayName -like "*$appName*") {
                $devicesWithApp += [pscustomobject]@{
                    DeviceName    = $device.DeviceName
                    OS            = $device.OperatingSystem
                    AppName       = $app.DisplayName
                    AppVersion    = $app.Version
                }
            }
        }
    }
}

# Sort the results by DeviceName
$sortedDevicesWithApp = $devicesWithApp | Sort-Object DeviceName

# Export the results to an Excel file
$outputFile = "C:\Users\ps2249\Documents\DevicesWithTeamsClassic.xlsx"

if ($sortedDevicesWithApp.Count -gt 0) {
    $sortedDevicesWithApp | Export-Excel -Path $outputFile -AutoSize -Title "Devices with Microsoft Teams Classic"
    Write-Host "Results exported to: $outputFile"
} else {
    Write-Host "No devices with the app '$appName' were found."
}

r/GraphAPI • • Jul 24 '24

Graph API Call Records for Teams

3 Upvotes

I want to be able to get as much data via Graph API for our Team's data. Specifically, Quality of Service, Remote Callers vs In room speakers (if possible), Having the usernames of those who are calling in to our conference rooms. Data that shows how many rooms are being used, how people have sent invites verses though that accepted.


r/GraphAPI • • Apr 19 '24

Get-MgDevice -All and also reporting device owner/user

1 Upvotes

I am trying to use Graph API via Powershell to create a list of all devices in Entra.

Get-MgDevice -All -Property AccountEnabled, DeviceId, DeviceOwnership, DisplayName, EnrollmentType, IsCompliant, IsManaged, OperatingSystem, ProfileType | select AccountEnabled, DeviceId, DeviceOwnership, DisplayName, EnrollmentType, IsCompliant, IsManaged, OperatingSystem, ProfileType | Export-CSV c:\Reporting\EntraDevices.csv -NoTypeInformation

That works well and gives me a good list of devices.

How do I add the UPN or UserID for each device as well?

This CSV will be going into PowerBi to enable me to do some reporting, so its critical I can link the user with the device.