├── Azure └── demo.ps1 ├── .gitignore ├── Intune ├── Intune_logs_troubleshooting.ps1 ├── Images │ ├── Example_1.png │ ├── Example_2.png │ ├── Example_3.png │ ├── Example_4.png │ ├── Example_5.png │ ├── Example_6.png │ └── Example_7.png ├── Connect_with_app_certificate.ps1 ├── List_and_backup_configuration_policy.ps1 ├── Deploy_store_app.ps1 ├── List_and_backup_all_profiles_policies.ps1 ├── IntuneGraphAppCert.md ├── Intune_device_management_logs.ps1 └── Intune_Audit_logs.ps1 ├── README.md ├── Learning_Tutorials ├── Images │ ├── .DS_Store │ ├── ge_1.png │ ├── ge_10.png │ ├── ge_2.png │ ├── ge_3.png │ ├── ge_4.png │ ├── ge_5.png │ ├── ge_6.png │ ├── ge_7.png │ ├── ge_8.png │ └── ge_9.png └── 01_Graph_explorer_and_powershell.md ├── SharePoint_Online ├── Base_connect.ps1 └── Working_with_sites.ps1 ├── Miscellaneous ├── Disable_Allow_Read_Bitlocker_Keys.ps1 └── Creating_Self-signed_Certificate.ps1 ├── Teams ├── Creating_a_channel.ps1 ├── Creating_a_team.ps1 ├── Manage_team_members.ps1 └── List_Infos_Teams.ps1 ├── Entra_ID ├── Modifying_Existing_Connection.ps1 ├── Use_query_parameters_customize_outputs.ps1 ├── Create_time_last_password.ps1 ├── Update_remove_user_photos.ps1 ├── Entra_Module.ps1 ├── List_all_your_enterprise_apps.ps1 ├── List_all_enterprise_apps_expiring_secret.ps1 ├── Investigate_compromised_enterprise_app.ps1 └── Managing_Users_Groups.ps1 ├── Installing_Microsoft_Graph_PowerShell_SDK.ps1 ├── Microsoft_365 ├── View_account _license_service_details.ps1 ├── View_Microsoft_365_licenses.ps1 ├── Defender │ └── Defender_alerts.ps1 └── Office_365_Management_API │ └── Investigate_logs.ps1 ├── Exchange └── Connect_Exchange_Online.ps1 └── Find_cmdlets_scopes_perms_connect.ps1 /Azure/demo.ps1: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _DS.Store -------------------------------------------------------------------------------- /Intune/Intune_logs_troubleshooting.ps1: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Intune/Images/Example_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Intune/Images/Example_1.png -------------------------------------------------------------------------------- /Intune/Images/Example_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Intune/Images/Example_2.png -------------------------------------------------------------------------------- /Intune/Images/Example_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Intune/Images/Example_3.png -------------------------------------------------------------------------------- /Intune/Images/Example_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Intune/Images/Example_4.png -------------------------------------------------------------------------------- /Intune/Images/Example_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Intune/Images/Example_5.png -------------------------------------------------------------------------------- /Intune/Images/Example_6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Intune/Images/Example_6.png -------------------------------------------------------------------------------- /Intune/Images/Example_7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Intune/Images/Example_7.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Microsoft Graph PowerShell SDK 2 | Manage Azure and Microsoft 365 with the Microsoft Graph PowerShell SDK! 3 | -------------------------------------------------------------------------------- /Learning_Tutorials/Images/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/.DS_Store -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_1.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_10.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_2.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_3.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_4.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_5.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_6.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_7.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_8.png -------------------------------------------------------------------------------- /Learning_Tutorials/Images/ge_9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomwechsler/Microsoft_Graph/HEAD/Learning_Tutorials/Images/ge_9.png -------------------------------------------------------------------------------- /SharePoint_Online/Base_connect.ps1: -------------------------------------------------------------------------------- 1 | Connect-MgGraph -Scopes "User.Read.All","Sites.Manage.All","Group.ReadWrite.All" 2 | 3 | Get-MgSite -SiteId root -------------------------------------------------------------------------------- /SharePoint_Online/Working_with_sites.ps1: -------------------------------------------------------------------------------- 1 | #Retrieve Site 2 | Get-MgSite -SiteId root 3 | 4 | #Search for Sites 5 | Get-MgSite -Search "Cardano" | Select-Object DisplayName, Description, WebUrl 6 | 7 | #Retrieve Site Columns 8 | Get-MgSite -Search "Traders" 9 | $site = Get-MgSite -Search "Traders" -Top 1 10 | Get-MgSiteColumn -SiteId $site.Id | Select-Object DisplayName 11 | 12 | #Retrieve Site Lists 13 | $site = Get-MgSite -Search "Traders" -Top 1 14 | Get-MgSiteList -SiteId $site.Id -------------------------------------------------------------------------------- /Miscellaneous/Disable_Allow_Read_Bitlocker_Keys.ps1: -------------------------------------------------------------------------------- 1 | Connect-MgGraph -Scopes Policy.ReadWrite.Authorization 2 | 3 | $authPolicyUri = "https://graph.microsoft.com/beta/policies/authorizationPolicy/authorizationPolicy" 4 | $body = @{ 5 | defaultUserRolePermissions = @{ 6 | allowedToReadBitlockerKeysForOwnedDevice = $false #Set this to $true to allow BitLocker self-service recovery 7 | } 8 | }| ConvertTo-Json 9 | 10 | Invoke-MgGraphRequest -Uri $authPolicyUri -Method PATCH -Body $body 11 | 12 | # Show current policy setting 13 | $authPolicy = Invoke-MgGraphRequest -Uri $authPolicyUri 14 | 15 | $authPolicy.defaultUserRolePermissions -------------------------------------------------------------------------------- /Miscellaneous/Creating_Self-signed_Certificate.ps1: -------------------------------------------------------------------------------- 1 | #Create the Certificate 2 | $cert = New-SelfSignedCertificate -Subject "CN={GraphCertificate}" -CertStoreLocation "Cert:\CurrentUser\My" ` 3 | -KeyExportPolicy Exportable -KeySpec Signature ` 4 | -KeyLength 4096 -KeyAlgorithm RSA -HashAlgorithm SHA256 5 | 6 | #Export the Created Certificate 7 | Export-Certificate -Cert $cert -FilePath "C:\Certs\{GraphCertificate}.cer" 8 | 9 | #Set the Password and Export as "PFX" 10 | $pwd = ConvertTo-SecureString -String "{Password}" -Force –AsPlainTextExport -PfxCertificate ` 11 | -Cert $cert -FilePath "C:\Certs\{GraphCertificate}.pfx" -Password $pwd 12 | -------------------------------------------------------------------------------- /Teams/Creating_a_channel.ps1: -------------------------------------------------------------------------------- 1 | #Core Connection for Managing Teams 2 | $scopes = @( 3 | "Team.Create" 4 | "TeamSettings.ReadWrite.All" 5 | "TeamsTab.ReadWrite.All" 6 | "TeamsTab.Create" 7 | "TeamMember.ReadWrite.All" 8 | "Group.ReadWrite.All" 9 | "GroupMember.ReadWrite.All" 10 | ) 11 | Connect-MgGraph -Scopes $scopes 12 | 13 | #Create a Team Channel 14 | $group = Get-MgGroup -Filter "DisplayName eq 'Ethereum'" 15 | 16 | $team = Get-MgTeam -TeamId $group.Id 17 | 18 | $channelname = "Traders" 19 | $channeldescription = "Ethereum Traders" 20 | 21 | $channel = New-MgTeamChannel -TeamId $team.Id -DisplayName $channelname -Description $channeldescription 22 | 23 | #List the new Team Channel 24 | Get-MgTeamChannel -TeamId $team.Id -ChannelId $channel.Id -------------------------------------------------------------------------------- /Intune/Connect_with_app_certificate.ps1: -------------------------------------------------------------------------------- 1 | #The detailed instructions can be found in the file IntuneGraphAppCert.md 2 | 3 | $certName = 'IntuneGraphAppCert' 4 | 5 | $cert = New-SelfSignedCertificate -Subject "CN=$certName" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256 -NotAfter (get-date).AddYears(1) 6 | 7 | Export-Certificate -Cert $cert -FilePath "C:\certs\$certName.cer" 8 | 9 | $TenantId = '77e01716-a6a2-4f99-b864-xxxxxxxxxxxx' 10 | $AppId = '5c14b994-2290-4f84-9069-xxxxxxxxxxxx' 11 | $certName = 'IntuneGraphAppCert' 12 | 13 | $Cert = Get-ChildItem -Path 'Cert:\CurrentUser\My' | Where-Object { $_.Subject -eq "CN=$CertName" } 14 | 15 | Connect-MgGraph -TenantId $TenantId -ClientId $AppId -Certificate $Cert 16 | 17 | #We check the permissions 18 | (Get-MgContext).Scopes -------------------------------------------------------------------------------- /Teams/Creating_a_team.ps1: -------------------------------------------------------------------------------- 1 | #Core Connection for Managing Teams 2 | $scopes = @( 3 | "Team.Create" 4 | "TeamSettings.ReadWrite.All" 5 | "TeamsTab.ReadWrite.All" 6 | "TeamsTab.Create" 7 | "TeamMember.ReadWrite.All" 8 | "Group.ReadWrite.All" 9 | "GroupMember.ReadWrite.All" 10 | ) 11 | Connect-MgGraph -Scopes $scopes 12 | 13 | #Retrieve Microsoft 365 Group and Team 14 | $group = Get-MgGroup -Filter "DisplayName eq 'Cardano'" 15 | 16 | Get-MgTeam -TeamId $group.Id 17 | 18 | #Create a New Team 19 | New-MgTeam -AdditionalProperties @{ 20 | "template@odata.bind" = "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"; 21 | "displayName" = "Ethereum"; 22 | "description" = "Ethereum Team"; 23 | } 24 | 25 | #List the new Microsoft Team 26 | $group = Get-MgGroup -Filter "DisplayName eq 'Ethereum'" 27 | 28 | Get-MgTeam -TeamId $group.Id 29 | -------------------------------------------------------------------------------- /Entra_ID/Modifying_Existing_Connection.ps1: -------------------------------------------------------------------------------- 1 | #Viewing Existing Connection Details 2 | 3 | #If needed 4 | Import-Module Microsoft.Graph 5 | 6 | #Connect to Microsoft 365 to Access Users and Groups 7 | Connect-MgGraph -Scopes "User.ReadWrite.All","Group.ReadWrite.All" 8 | 9 | #Connections 10 | #Scopes are required for each connection 11 | #Scope permissions are for the current session (unless using an Azure App Registration) 12 | #Extra needed permissions require re-connecting with the specified scopes 13 | 14 | #View Current Connection Details 15 | Get-MgContext 16 | (Get-MgContext).AuthType 17 | (Get-MgContext).Scopes 18 | 19 | #Reconnect Connection With Updated Scopes 20 | #Original Connection 21 | Connect-MgGraph -Scopes "User.ReadWrite.All","Group.ReadWrite.All" 22 | 23 | #Update Connection to Allow "Group Members" 24 | Connect-MgGraph -Scopes "User.ReadWrite.All","Group.ReadWrite.All","GroupMember.ReadWrite.All" -------------------------------------------------------------------------------- /Teams/Manage_team_members.ps1: -------------------------------------------------------------------------------- 1 | #Core Connection for Managing Teams 2 | $scopes = @( 3 | "Team.Create" 4 | "TeamSettings.ReadWrite.All" 5 | "TeamsTab.ReadWrite.All" 6 | "TeamsTab.Create" 7 | "TeamMember.ReadWrite.All" 8 | "Group.ReadWrite.All" 9 | "GroupMember.ReadWrite.All" 10 | ) 11 | Connect-MgGraph -Scopes $scopes 12 | 13 | #Retrieve User Details 14 | $email = "james.west@tomsazure.ch" 15 | $user = Get-MgUser -UserId $email 16 | 17 | #Retrieve Team and Add an Owner 18 | $group = Get-MgGroup -Filter "DisplayName eq 'Ethereum'" 19 | 20 | $team = Get-MgTeam -TeamId $group.Id 21 | 22 | $ownerproperties = @{ 23 | "@odata.type" = "#microsoft.graph.aadUserConversationMember"; 24 | "user@odata.bind" = "https://graph.microsoft.com/beta/users/" + $user.Id } 25 | 26 | $role = "owner" 27 | 28 | New-MgTeamMember -TeamId $team.Id -Roles $role -AdditionalProperties $ownerproperties 29 | 30 | #Retrieve Team Member and Owner for the Team 31 | Get-MgTeamMember -TeamId $team.Id | Select-Object -Property Roles,DisplayName -------------------------------------------------------------------------------- /Entra_ID/Use_query_parameters_customize_outputs.ps1: -------------------------------------------------------------------------------- 1 | #Count parameter 2 | Get-MgUser -ConsistencyLevel eventual -Count userCount 3 | 4 | $userCount 5 | 6 | #Expand parameter 7 | Get-MgGroup 8 | 9 | Get-MgGroup -GroupId '011368db-4b82-4dc4-a611-8dbb0e423686' -Expand members | 10 | Select-Object -ExpandProperty members 11 | 12 | Get-MgGroup -GroupId '011368db-4b82-4dc4-a611-8dbb0e423686' -Expand members | 13 | Select-Object -ExpandProperty members | 14 | Select-Object -ExpandProperty Id 15 | 16 | #Filter parameter 17 | Get-MgUser -Filter "startsWith(DisplayName, 'J')" 18 | 19 | #OrderBy parameter 20 | Get-MgUser -OrderBy DisplayName 21 | 22 | #Search parameter 23 | Get-MgUser -ConsistencyLevel eventual -Count UserCount -Search '"DisplayName:St"' 24 | 25 | #Select parameter 26 | Get-MgUser | Select-Object Id, DisplayName 27 | 28 | #Top parameter 29 | Get-MgUser -Top 5 30 | 31 | #Error handling for query parameters 32 | Get-MgUser -Filter "Contains(DisplayName, 'Test')" 33 | 34 | #Some requests will return an error message if a specified query parameter isn't supported. 35 | #For example, you can't use the -Contains operator on the DisplayName property. -------------------------------------------------------------------------------- /Intune/List_and_backup_configuration_policy.ps1: -------------------------------------------------------------------------------- 1 | #Use PowerShell Version 5.1 not 7 2 | Install-Module -Name Microsoft.Graph.Intune -Verbose 3 | 4 | #Import the Microsoft Graph Intune module 5 | Import-Module -Name Microsoft.Graph.Intune -Verbose 6 | 7 | #Connect to the Microsoft Intune service 8 | Connect-MSGraph 9 | 10 | #Retrieve a list of all profiles and policies in Intune 11 | $policies = Get-IntuneDeviceConfigurationPolicy 12 | 13 | #Create backup folder if it doesn't exist 14 | $backupFolder = "C:\IntuneBackup" 15 | if (-not (Test-Path -Path $backupFolder -PathType Container)) { 16 | New-Item -ItemType Directory -Path $backupFolder | Out-Null 17 | } 18 | 19 | #Show display name and creation date of each policy in a table format with green color in the terminal, and export to a JSON file in the backup folder 20 | $table = @() 21 | foreach ($policy in $policies) { 22 | $row = [pscustomobject]@{ 23 | "Display Name" = $policy.DisplayName 24 | "Creation Date" = $policy.CreatedDateTime 25 | } 26 | $table += $row 27 | $policy | ConvertTo-Json | Out-File -FilePath "$backupFolder\$($policy.DisplayName).json" 28 | } 29 | $table | Format-Table -AutoSize -------------------------------------------------------------------------------- /Intune/Deploy_store_app.ps1: -------------------------------------------------------------------------------- 1 | #Search with winget for the app you want to deploy 2 | winget search "Cisco" 3 | 4 | #Search for the winget app that is an msstore app 5 | winget search -s msstore "Cisco" 6 | 7 | #To make some space below 8 | Set-Location C:\ 9 | Clear-Host 10 | 11 | #Istall the module. (You need admin on the machine.) 12 | Install-Module Microsoft.Graph -AllowClobber -Verbose -Force 13 | 14 | #Connect to the graph (incl. necessary permissions) DeviceManagementApps.ReadWrite.All, DeviceManagementApps.Read.All 15 | Connect-MgGraph 16 | 17 | #We check the permissions 18 | (Get-MgContext).Scopes 19 | 20 | #Search for specific cmdlets 21 | Get-Command *-mgGraphRequest* 22 | 23 | #Create some variables 24 | $displayName = "Cisco Any Connect" 25 | $ApplicationId = "9WZDNCRDJ8LH" 26 | 27 | #Create the body 28 | $body = @" 29 | { 30 | "@odata.type": "#microsoft.graph.winGetApp", 31 | "displayName": "$($displayName)", 32 | "packageIdentifier": "$($ApplicationId)", 33 | "installExperience": { 34 | "runAsAccount": "system" 35 | } 36 | } 37 | "@ 38 | 39 | #Create the URI 40 | $uri = 'https://graph.microsoft.com/beta/deviceAppManagement/mobileApps' 41 | 42 | #Create the app 43 | Invoke-MgGraphRequest -Method POST -Body $body -Uri $uri -------------------------------------------------------------------------------- /Entra_ID/Create_time_last_password.ps1: -------------------------------------------------------------------------------- 1 | #Install Microsoft Graph Module 2 | Install-Module Microsoft.Graph -AllowClobber -Force 3 | 4 | #Import Microsoft Graph Module if needed 5 | Import-Module Microsoft.Graph 6 | 7 | #Time range 8 | $date = (Get-Date).AddDays(-60) 9 | 10 | #A variable for later output 11 | $properties = 'AccountEnabled', 'UserPrincipalName','Id','CreatedDateTime','LastPasswordChangeDateTime' 12 | 13 | #Connect to the cloud (incl. necessary permissions) 14 | Connect-Graph -Scopes User.Read.All, Directory.AccessAsUser.All, User.ReadBasic.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All 15 | 16 | #We check the permissions 17 | (Get-MgContext).Scopes 18 | 19 | #List the users and store them in a variable 20 | $mgUsers = Get-MgUser -All -Select $properties 21 | 22 | #Let's look at the list 23 | $mgUsers 24 | 25 | #How many are there? 26 | $mgUsers.count 27 | 28 | #Get-Member to get the details 29 | Get-MgUser | Get-Member 30 | 31 | #Creation date and last password change 32 | $InfoUsers = $mgUsers | Where-Object { 33 | $_.CreatedDateTime -lt $date -and 34 | $_.LastPasswordChangeDateTime -lt $date 35 | } 36 | 37 | #How many have we found (No longer the same number)? 38 | $InfoUsers.count 39 | 40 | #We'll take a look at it 41 | $InfoUsers | Format-Table $properties -------------------------------------------------------------------------------- /Entra_ID/Update_remove_user_photos.ps1: -------------------------------------------------------------------------------- 1 | #Set the Execution Policy (Windows) 2 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 3 | 4 | #Install Microsoft Graph PowerShell SDK 5 | Install-Module Microsoft.Graph -Force -Verbose -AllowClobber 6 | 7 | #Verify the Installation 8 | Get-InstalledModule Microsoft.Graph 9 | 10 | #We search for the permissions 11 | Find-MgGraphCommand -Command Get-MgUserPhoto | Select-Object -First 1 -ExpandProperty Permissions 12 | 13 | Find-MgGraphCommand -Command Set-MgUserPhotoContent | Select-Object -First 1 -ExpandProperty Permissions 14 | 15 | #Connect to Microsoft Graph using Scopes 16 | Connect-MgGraph -Scopes "User.ReadWrite.All" 17 | 18 | #We check the permissions 19 | (Get-MgContext).Scopes 20 | 21 | #Get information about users 22 | Get-MgUser 23 | 24 | #Get information about user photos 25 | Get-MgUserPhoto -UserId NestorW@63k57q.onmicrosoft.com 26 | 27 | #Add user photos 28 | Set-MgUserPhotoContent -UserId NestorW@63k57q.onmicrosoft.com -InFile "C:\Upload\NestorW.png" 29 | 30 | #Download user photos 31 | Get-MgUserPhotoContent -UserId NestorW@63k57q.onmicrosoft.com -OutFile "C:\Download\NestorW.png" 32 | 33 | #Remove user photos 34 | Remove-MgUserPhoto -UserId NestorW@63k57q.onmicrosoft.com 35 | 36 | #Disconnect from Microsoft Graph 37 | Disconnect-MgGraph 38 | -------------------------------------------------------------------------------- /Installing_Microsoft_Graph_PowerShell_SDK.ps1: -------------------------------------------------------------------------------- 1 | #Set the Execution Policy (Windows) 2 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 3 | 4 | #Installing the Module 5 | 6 | #Installing the Graph PowerShell module with no previous versions installed 7 | Install-module Microsoft.Graph 8 | 9 | #If upgrading from a preview modules, run install-module with AllowClobber and Force parameter to avoid command name conflicts 10 | Install-Module Microsoft.Graph -AllowClobber -Force -Verbose 11 | 12 | #Updating from an earlier version of MS Graph PowerShell installed from PS Gallery 13 | Update-module Microsoft.Graph 14 | 15 | #Uninstalling the old preview version, before installing the new 16 | 17 | #Remove the main meta module 18 | Uninstall-Module Microsoft.Graph 19 | 20 | #Remove all the dependent modules 21 | Get-InstalledModule Microsoft.Graph.* | ForEach-Object { if($_.Name -ne "Microsoft.Graph.Authentication"){ Uninstall-Module $_.Name } } 22 | 23 | #Update the authentication module 24 | Install-Module Microsoft.Graph.Authentication -Repository PSGallery -force 25 | 26 | #Or uninstall the authentication module 27 | Uninstall-Module Microsoft.Graph.Authentication 28 | 29 | #The Modules are installed in the user profile 30 | ' "$env:USERPROFILE\Documents\PowerShell\Modules" or "C:\Users\admin\Documents\PowerShell\Modules" ' -------------------------------------------------------------------------------- /Microsoft_365/View_account _license_service_details.ps1: -------------------------------------------------------------------------------- 1 | #Reading user properties including license details requires the User.Read.All 2 | Connect-Graph -Scopes User.ReadWrite.All, Organization.Read.All 3 | 4 | #Next, list the license plans for your tenant with this command. 5 | Get-MgSubscribedSku 6 | 7 | #Use these commands to list the services that are available in each licensing plan. 8 | $allSKUs = Get-MgSubscribedSku -Property SkuPartNumber, ServicePlans 9 | 10 | $allSKUs | ForEach-Object { 11 | Write-Host "Service Plan:" $_.SkuPartNumber 12 | $_.ServicePlans | ForEach-Object {$_} 13 | } 14 | 15 | #Use these commands to list the licenses that are assigned to a user account. 16 | Get-MgUserLicenseDetail -UserId "mike.braun@contoso.com" 17 | 18 | #To view all the Microsoft 365 services that a user has access to 19 | (Get-MgUserLicenseDetail -UserId "mike.braun@contoso.com" -Property ServicePlans).ServicePlans 20 | 21 | (Get-MgUserLicenseDetail -UserId "mike.braun@contoso.com" -Property ServicePlans)[0].ServicePlans 22 | 23 | #To view all the services for a user who has been assigned multiple licenses 24 | $userUPN="mike.braun@contoso.com" 25 | 26 | $allLicenses = Get-MgUserLicenseDetail -UserId $userUPN -Property SkuPartNumber, ServicePlans 27 | $allLicenses | ForEach-Object { 28 | Write-Host "License:" $_.SkuPartNumber 29 | $_.ServicePlans | ForEach-Object {$_} 30 | } -------------------------------------------------------------------------------- /Microsoft_365/View_Microsoft_365_licenses.ps1: -------------------------------------------------------------------------------- 1 | #Reading subscription license plans requires the Organization.Read.All 2 | Connect-Graph -Scopes Organization.Read.All 3 | 4 | #To view summary information about your current licensing plans 5 | Get-MgSubscribedSku | Select-Object -Property Sku*, ConsumedUnits -ExpandProperty PrepaidUnits | Format-List 6 | 7 | #The results contain: 8 | 9 | #SkuPartNumber: Shows the available licensing plans for your organization. For example, ENTERPRISEPACK is the license plan name for Office 365 Enterprise E3. 10 | 11 | #Enabled: Number of licenses that you've purchased for a specific licensing plan. 12 | 13 | #ConsumedUnits: Number of licenses that you've assigned to users from a specific licensing plan. 14 | 15 | #To view details about the Microsoft 365 services that are available in all of your license plans, first display a list of your license plans. 16 | Get-MgSubscribedSku 17 | 18 | #Next, store the license plans information in a variable. 19 | $licenses = Get-MgSubscribedSku 20 | 21 | #Next, display the services in a specific license plan. 22 | $licenses[].ServicePlans 23 | # is an integer that specifies the row number of the license plan from the display of the Get-MgSubscribedSku | Select SkuPartNumber command, minus 1. 24 | 25 | Get-MgSubscribedSku | Select-Object SkuPartNumber 26 | 27 | #Then the command to display the services for the ENTERPRISEPREMIUM license plan is this: 28 | 29 | #SkuPartNumber 30 | #------------- 31 | #Microsoft_Intune_Suite 32 | #ENTERPRISEPREMIUM 33 | 34 | $licenses[1].ServicePlans -------------------------------------------------------------------------------- /Entra_ID/Entra_Module.ps1: -------------------------------------------------------------------------------- 1 | #The graph module 2 | Install-Module microsoft.graph -Scope CurrentUser -Force -Verbose 3 | 4 | #Get infos 5 | Get-Module -ListAvailable | Where-Object { $_.Name -like 'Microsoft.Graph.*' } 6 | Get-Command -module microsoft.graph.Users | Select-Object -Unique Noun | Sort-Object Noun 7 | 8 | #Install the module Entra PowerShell module 9 | Install-Module Microsoft.Graph.Entra -AllowPrerelease -Repository PSGallery -Force -Verbose 10 | 11 | Update-Module -Name Microsoft.Graph.Entra -AllowPrerelease #keep up-to-date 12 | 13 | Get-Module microsoft.graph.entra 14 | 15 | #If you want the Beta version 16 | Install-Module Microsoft.Graph.Entra.Beta -AllowPrerelease -Repository PSGallery -Force 17 | 18 | #Connect to your tenant 19 | Connect-MgGraph -Scopes 'User.Read.All' 20 | 21 | #Or use 22 | Connect-Entra -Scopes 'User.Read.All' 23 | 24 | #Check current consented scopes 25 | (Get-MgContext).Scopes 26 | 27 | #View the objects supported by the Entra module 28 | Get-Command -Module microsoft.graph.entra | Select-Object -Unique Noun | Sort-Object Noun 29 | 30 | Get-EntraUser -SearchString "Harry" | Format-Table DisplayName, Mail 31 | 32 | #To see more detail, the REST call etc 33 | Get-EntraUser -SearchString "Harry" -Debug 34 | 35 | 36 | #No pipelining :-( 37 | Get-MgGroup -Filter "DisplayName eq 'Bitcoin Traders'" | Get-MgGroupMember 38 | 39 | #Yay! 40 | Get-EntraGroup -Filter "DisplayName eq 'Bitcoin Traders'" | Get-EntraGroupMember | Format-Table DisplayName, city 41 | 42 | 43 | #Alias 44 | Enable-EntraAzureADAlias 45 | Get-Alias -Name *AzureAD* 46 | Get-Alias -Definition Get-EntraUser 47 | 48 | Get-AzureADUser -SearchString "Harry" | Format-Table DisplayName, Mail 49 | -------------------------------------------------------------------------------- /Exchange/Connect_Exchange_Online.ps1: -------------------------------------------------------------------------------- 1 | Set-Location C:\ 2 | Clear-Host 3 | 4 | #Set the Execution Policy (Windows) 5 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 6 | 7 | #Install into the Current User Scope 8 | Install-Module Microsoft.Graph -Scope CurrentUser -AllowClobber -Verbose -Force 9 | 10 | #If needed 11 | Import-Module Microsoft.Graph 12 | 13 | #Connection for Creating, Reading, Updating, and Deleting Mail 14 | $scopes = @("Mail.ReadWrite") 15 | Connect-MgGraph -Scopes $scopes 16 | 17 | #We search for my UserID 18 | Get-MgUser 19 | 20 | Get-MgUser -All | Format-List ID, DisplayName, Mail, UserPrincipalName 21 | 22 | #We search for the permissions 23 | Find-MgGraphCommand -command Get-MgUserMailFolder | Select-Object -First 1 -ExpandProperty Permissions 24 | 25 | Find-MgGraphCommand -command Get-MgUserMailboxSetting | Select-Object -First 1 -ExpandProperty Permissions 26 | 27 | #An example 28 | $User = Get-MgUser -UserId "b41b6fbd-8da5-4e68-a2f3-2288d682f1f0" 29 | $mailfolders = Get-MgUserMailFolder -UserId $User.Id -All 30 | $mailfolders 31 | 32 | #Connection for Sending Mail as Users in the Organization 33 | $scopes = @("SMTP.Send") 34 | Connect-MgGraph -Scopes $scopes 35 | 36 | #Connection for Creating, Reading, Updating, and Deleting Events in User Calendars 37 | $scopes = @("Calendars.ReadWrite") 38 | Connect-MgGraph -Scopes $scopes 39 | 40 | #An example 41 | $User = Get-MgUser -UserId "b41b6fbd-8da5-4e68-a2f3-2288d682f1f0" 42 | $calendar = Get-MgUserCalendar -UserId $User.Id -All 43 | $calendar 44 | 45 | #Core Connection for Managing Mail and Calendar 46 | $scopes = @("Mail.ReadWrite","Calendars.ReadWrite") 47 | Connect-MgGraph -Scopes $scopes -------------------------------------------------------------------------------- /Entra_ID/List_all_your_enterprise_apps.ps1: -------------------------------------------------------------------------------- 1 | #Install the Microsoft Graph PowerShell SDK module 2 | Install-Module Microsoft.Graph 3 | 4 | #Install the Az PowerShell module 5 | Install-Module Az -AllowClobber -Force -Verbose 6 | 7 | # Authenticate with your Azure AD account 8 | Connect-MgGraph -Scopes 'Application.Read.All','AppRoleAssignment.ReadWrite.All' 9 | 10 | #Connect to Azure 11 | Connect-AzAccount 12 | 13 | #Get all user assigned managed identities in your tenant 14 | $UserAssignedManagedIdentities = Get-MgServicePrincipal -Filter "Tags/any(t:t eq 'WindowsAzureActiveDirectoryIntegratedApp')" 15 | 16 | #For each user assigned managed identity, check if it is assigned to a resource 17 | foreach ($UserAssignedManagedIdentity in $UserAssignedManagedIdentities) { 18 | # Get the resource ID of the user assigned managed identity 19 | $UserAssignedManagedIdentityResourceId = $UserAssignedManagedIdentity.AppId 20 | 21 | #Get all resources 22 | $Resources = Get-AzResource 23 | 24 | #Filter resources that have an identity 25 | $ResourcesWithIdentity = $Resources | Where-Object {$_.Identity -ne $null} 26 | 27 | #Search for all resources using this user assigned managed identity 28 | $ResourcesUsingUserAssignedManagedIdentity = $ResourcesWithIdentity | Where-Object {$_.Identity.UserAssignedIdentities.Keys -contains $UserAssignedManagedIdentityResourceId} 29 | 30 | #If no resource is found, add the user assigned managed identity to the list 31 | if ($ResourcesUsingUserAssignedManagedIdentity.Count -eq 0) { 32 | $UnusedUserAssignedManagedIdentities += $UserAssignedManagedIdentity 33 | } 34 | } 35 | 36 | # Output the number and names of the unused user assigned managed identities. 37 | Write-Host "There are $($UnusedUserAssignedManagedIdentities.Count) unused user assigned managed identities in your tenant:" 38 | foreach ($UnusedUserAssignedManagedIdentity in $UnusedUserAssignedManagedIdentities) { 39 | Write-Host "- $($UnusedUserAssignedManagedIdentity.DisplayName)" 40 | } -------------------------------------------------------------------------------- /Teams/List_Infos_Teams.ps1: -------------------------------------------------------------------------------- 1 | #Install Microsoft Graph Module 2 | Install-Module Microsoft.Graph -AllowClobber -Force 3 | 4 | $scopes = @( 5 | 6 | "Group.ReadWrite.All", 7 | 8 | "GroupMember.ReadWrite.All", 9 | 10 | "TeamsApp.ReadWrite.All", 11 | 12 | "TeamsAppInstallation.ReadWriteForTeam", 13 | 14 | "TeamsAppInstallation.ReadWriteSelfForTeam", 15 | 16 | "TeamSettings.ReadWrite.All", 17 | 18 | "TeamsTab.ReadWrite.All", 19 | 20 | "TeamMember.ReadWrite.All" 21 | 22 | ) 23 | 24 | #Connect to Graph 25 | Connect-MgGraph -Scopes $scopes 26 | 27 | #List the groups 28 | Get-MgGroup | Format-List Id, DisplayName, Description, GroupTypes 29 | 30 | $group = Get-MgGroup -Filter "DisplayName eq 'Cardano'" 31 | 32 | #Retrieve Teams by ID 33 | $team = Get-MgTeam -TeamId $group.Id 34 | Write-Host $team.DisplayName 35 | 36 | #View All Properties About Selected Team 37 | $team = Get-MgTeam -TeamId $group.Id 38 | $team | Select-Object * 39 | 40 | #View All Members of a Team 41 | $team = Get-MgTeam -TeamId $group.Id 42 | $members = Get-MgTeamMember -TeamId $team.Id 43 | $members | Select-Object DisplayName 44 | 45 | #Create a new team 46 | $params = @{ 47 | "Template@odata.bind" = "https://graph.microsoft.com/v1.0/teamsTemplates('standard')" 48 | DisplayName = 'Marketing' 49 | Description = 'Team for the marketing' 50 | } 51 | New-MgTeam -BodyParameter $params 52 | 53 | #Did it work? 54 | Get-MgTeam 55 | 56 | #Lets update some properties 57 | $params = @{ 58 | MemberSettings = @{ 59 | AllowCreateUpdateChannels = "true" # 60 | } 61 | MessagingSettings = @{ 62 | AllowUserEditMessages = "true" # 63 | AllowUserDeleteMessages = "false" # 64 | } 65 | FunSettings = @{ 66 | AllowGiphy = "true" # 67 | GiphyContentRating = "moderate" # 68 | } 69 | } 70 | 71 | Update-MgTeam -TeamId 03f3cacb-4d0a-4102-942f-67d2c5b80445 -BodyParameter $params 72 | 73 | #Did it work? 74 | Get-MgTeam -TeamId 03f3cacb-4d0a-4102-942f-67d2c5b80445 | Select-Object -Property FunSettings -ExpandProperty FunSettings -------------------------------------------------------------------------------- /Microsoft_365/Defender/Defender_alerts.ps1: -------------------------------------------------------------------------------- 1 | #Authenticate with Microsoft Graph 2 | Connect-MgGraph 3 | 4 | #Get SuspiciousActivity alerts 5 | $alerts = Get-MgSecurityAlert -Filter "Category eq 'SuspiciousActivity'" 6 | 7 | foreach ($alert in $alerts) { 8 | Write-Host "Alert ID: $($alert.Id)" 9 | Write-Host "Title: $($alert.Title)" 10 | Write-Host "Description: $($alert.Description)" 11 | Write-Host "Status: $($alert.Status)" 12 | Write-Host "Severity: $($alert.Severity)" 13 | Write-Host "--------------------------" 14 | } 15 | 16 | #Get Malware alerts 17 | $alerts = Get-MgSecurityAlert -Filter "Category eq 'Malware'" 18 | 19 | foreach ($alert in $alerts) { 20 | Write-Host "Alert ID: $($alert.Id)" 21 | Write-Host "Title: $($alert.Title)" 22 | Write-Host "Description: $($alert.Description)" 23 | Write-Host "Status: $($alert.Status)" 24 | Write-Host "Severity: $($alert.Severity)" 25 | Write-Host "--------------------------" 26 | } 27 | 28 | #Get UnwantedSoftware alerts 29 | $alerts = Get-MgSecurityAlert -Filter "Category eq 'UnwantedSoftware'" 30 | 31 | foreach ($alert in $alerts) { 32 | Write-Host "Alert ID: $($alert.Id)" 33 | Write-Host "Title: $($alert.Title)" 34 | Write-Host "Description: $($alert.Description)" 35 | Write-Host "Status: $($alert.Status)" 36 | Write-Host "Severity: $($alert.Severity)" 37 | Write-Host "--------------------------" 38 | } 39 | 40 | #Get DefenseEvasion alerts 41 | $alerts = Get-MgSecurityAlert -Filter "Category eq 'DefenseEvasion'" 42 | 43 | foreach ($alert in $alerts) { 44 | Write-Host "Alert ID: $($alert.Id)" 45 | Write-Host "Title: $($alert.Title)" 46 | Write-Host "Description: $($alert.Description)" 47 | Write-Host "Status: $($alert.Status)" 48 | Write-Host "Severity: $($alert.Severity)" 49 | Write-Host "--------------------------" 50 | } 51 | 52 | #Get CommandAndControl alerts 53 | $alerts = Get-MgSecurityAlert -Filter "Category eq 'CommandAndControl'" 54 | 55 | foreach ($alert in $alerts) { 56 | Write-Host "Alert ID: $($alert.Id)" 57 | Write-Host "Title: $($alert.Title)" 58 | Write-Host "Description: $($alert.Description)" 59 | Write-Host "Status: $($alert.Status)" 60 | Write-Host "Severity: $($alert.Severity)" 61 | Write-Host "--------------------------" 62 | } 63 | 64 | #Disconnect from Microsoft Graph 65 | Disconnect-MgGraph -------------------------------------------------------------------------------- /Intune/List_and_backup_all_profiles_policies.ps1: -------------------------------------------------------------------------------- 1 | #Install the msal.ps module 2 | Install-Module -Name msal.ps -AllowClobber -Verbose -Force 3 | 4 | #I am working with an app registration, replace the values with your own (be sure that your app has the needed permissions) 5 | #Device.Read.All 6 | #DeviceManagementConfiguration.Read.All 7 | #DeviceManagementConfiguration.ReadWrite.All 8 | 9 | $params = @{ 10 | ClientId = '12345678-ee4e-498b-b449-5c949d5caf14' 11 | TenantId = '87654321-a6a2-4f99-b864-164035e9e465' 12 | DeviceCode = $true 13 | } 14 | $authHeaders = @{Authorization = (Get-MsalToken @params).CreateAuthorizationHeader()} 15 | 16 | ##Search for the policies and profiles## 17 | 18 | #Compliance policies 19 | $compliancePoliciesRequest = (Invoke-RestMethod -Headers $authHeaders -Uri "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies" -Method Get) 20 | $compliancePolicies = $compliancePoliciesRequest.value 21 | 22 | #Configuration policies 23 | $configurationPoliciesRequest = (Invoke-RestMethod -Headers $authHeaders -Uri "https://graph.microsoft.com/beta/deviceManagement/deviceConfigurations" -Method Get) 24 | $configurationPolicies = $ConfigurationPoliciesRequest.value 25 | 26 | #Export compliance policies (be sure that the export directory exists - C:\Temp\) 27 | $location = "C:\Temp" 28 | try{ 29 | foreach($policy in $compliancePolicies){ 30 | $filePath = "$($location)\Compliance - $($policy.displayName).json" 31 | $policy | convertto-json -Depth 10 | out-file $filePath 32 | write-host "Exported policy: $($policy.displayName)" -ForegroundColor green 33 | } 34 | } 35 | catch{ 36 | write-host "Error: $($_.Exception.Message)" -ForegroundColor red 37 | } 38 | 39 | #Export configuration profiles 40 | try{ 41 | foreach($policy in $ConfigurationPolicies){ 42 | $filePath = "$($location)\Configuration - $($policy.displayName).json" 43 | $policy | convertto-json -Depth 10 | out-file $filePath 44 | $Clean = Get-Content $filePath | Select-String -Pattern '"id":', '"createdDateTime":', '"modifiedDateTime":', '"version":', '"supportsScopeTags":' -notmatch 45 | $Clean | Out-File -FilePath $filePath 46 | write-host "Exported profiles: $($policy.displayName)" -ForegroundColor green 47 | } 48 | } 49 | catch{ 50 | write-host "Error: $($_.Exception.Message)" -ForegroundColor red 51 | } 52 | 53 | #That's it! -------------------------------------------------------------------------------- /Intune/IntuneGraphAppCert.md: -------------------------------------------------------------------------------- 1 | # Connect securely to Intune with Microsoft Graph and PowerShell! 2 | In this example, we use an app registration in Microsoft Entra ID and a certificate created on the local machine. 3 | 4 | ## Create and export the certificate 5 | 6 | **I use Visual Studio Code and PowerShell 7** 7 | 8 | ``` 9 | $certName = 'IntuneGraphAppCert' 10 | 11 | $cert = New-SelfSignedCertificate -Subject "CN=$certName" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256 -NotAfter (get-date).AddYears(1) 12 | 13 | Export-Certificate -Cert $cert -FilePath "C:\certs\$certName.cer" 14 | ``` 15 | 16 | > Note: The certificate is created in the local certificate store and exported to the folder C:\certs. The certificate is valid for one year. 17 | 18 | The Certificate 19 | 20 | ## Create an app registration in Microsoft Azure AD 21 | 22 | 1. Go to the Azure portal and create a new app registration in Azure AD. 23 | 24 | In the Entra ID 25 | 26 | 2. Give the app a name and notice the following. 27 | 28 | The ID's 29 | 30 | 4. Go to the API permissions and add the following permissions (These serve only as an example). 31 | 32 | The API permissions 33 | 34 | 5. Do not forget to grant admin consent. 35 | 36 | The admin consent 37 | 38 | 6. Go to the certificate and secrets and upload the certificate. 39 | 40 | The certificate 41 | 42 | ## Back in PowerShell 43 | 44 | 1. Install the Microsoft.Graph. 45 | 46 | ``` 47 | Install-Module -Name Microsoft.Graph -Verbose -Force -AllowClobber 48 | ``` 49 | 50 | 2. Import the Microsoft.Graph module. 51 | 52 | ``` 53 | Import-Module Microsoft.Graph 54 | ``` 55 | 56 | 3. Create some variables. 57 | 58 | ``` 59 | $TenantId = '77e01716-a6a2-4f99-b864-xxxxxxxxxxxx' 60 | $AppId = '5c14b994-2290-4f84-9069-xxxxxxxxxxxx' 61 | $certName = 'IntuneGraphAppCert' 62 | 63 | $Cert = Get-ChildItem -Path 'Cert:\CurrentUser\My' | Where-Object { $_.Subject -eq "CN=$CertName" } 64 | ``` 65 | 66 | 4. Connect to Microsoft Graph. 67 | 68 | ``` 69 | Connect-MgGraph -TenantId $TenantId -ClientId $AppId -Certificate $Cert 70 | ``` 71 | 72 | 5. We check the permissions. 73 | ``` 74 | (Get-MgContext).Scopes 75 | ``` 76 | 77 | The permissions 78 | 79 | --- 80 | ## *HAPPY CONNECTING!* 81 | --- -------------------------------------------------------------------------------- /Find_cmdlets_scopes_perms_connect.ps1: -------------------------------------------------------------------------------- 1 | #Finding Available cmdlets 2 | Import-Module Microsoft.Graph 3 | 4 | Get-Command -Module Microsoft.Graph* 5 | 6 | Get-Command -Module Microsoft.Graph* *Team* 7 | 8 | Get-Command -Module Microsoft.Graph* *User* 9 | 10 | Get-Command -Module Microsoft.Graph* -Noun *Group* 11 | 12 | Get-Command -Module Microsoft.Graph.Authentication 13 | 14 | 15 | #Getting Help for a cmdlet 16 | Get-Help Get-MgUser 17 | 18 | Get-Help Get-MgUser -Category Cmdlet 19 | 20 | Get-Help Get-MgUser -Category Function 21 | 22 | Get-Help Get-MgUser -Detailed 23 | 24 | Get-Help Get-MgUser -Full 25 | 26 | Get-Help Get-MgUser -ShowWindow 27 | 28 | #Connect to Microsoft 365 using Scopes 29 | #Scopes to Manage Users and Groups with Full Read Write Access 30 | $scopes = @( 31 | "User.ReadWrite.All" 32 | "Directory.ReadWrite.All" 33 | "Group.ReadWrite.All" 34 | ) 35 | 36 | #Scopes to Create Teams 37 | $scopes = @("Team.Create" 38 | "Group.ReadWrite.All" 39 | ) 40 | 41 | #Scopes to Manage SharePoint Online Sites and Files 42 | $scopes = @("Sites.FullControl.All" 43 | "Sites.Manage.All" 44 | "Sites.ReadWrite.All" 45 | "Files.ReadWrite.All" 46 | "Files.ReadWrite.AppFolder" 47 | ) 48 | 49 | #Scopes to Manage Mail 50 | $scopes = @("Mail.ReadWrite" 51 | "Mail.ReadWrite.Shared" 52 | "Mail.Send" 53 | ) 54 | 55 | #Finding Available Permissions 56 | #SharePoint Sites 57 | Find-MgGraphPermission sites -PermissionType Delegated 58 | 59 | Find-MgGraphPermission sites -PermissionType Application 60 | 61 | #Microsoft Teams 62 | Find-MgGraphPermission teams -PermissionType Delegated 63 | 64 | Find-MgGraphPermission teams -PermissionType Application 65 | 66 | #Users 67 | Find-MgGraphPermission user -PermissionType Delegated 68 | 69 | Find-MgGraphPermission user -PermissionType Application 70 | 71 | #eDiscovery 72 | Find-MgGraphPermission ediscovery -PermissionType Delegated 73 | 74 | #We search for the permissions 75 | Find-MgGraphCommand -Command Get-MgUserMailFolder | Select-Object -First 1 -ExpandProperty Permissions 76 | 77 | Find-MgGraphCommand -Command Get-MgUserMailboxSetting | Select-Object -First 1 -ExpandProperty Permissions 78 | 79 | #Connect Using the Standard Command and Scopes 80 | $scopes = @("User.ReadWrite.All" 81 | "Directory.Read.All" 82 | "Group.Read.All" 83 | ) 84 | Connect-MgGraph -Scopes $scopes 85 | 86 | #Connect Using an Azure App Registration 87 | Connect-MgGraph -ClientId "your ClientId" -TenantId "your TenantId" -CertificateThumbprint "your CertificateThumbprint" 88 | 89 | #We check the permissions 90 | (Get-MgContext).Scopes -------------------------------------------------------------------------------- /Entra_ID/List_all_enterprise_apps_expiring_secret.ps1: -------------------------------------------------------------------------------- 1 | #Install the Microsoft Graph PowerShell SDK module 2 | Install-Module Microsoft.Graph -Verbose -AllowClobber -Force 3 | 4 | #Authenticate with your Entra ID account 5 | Connect-MgGraph -Scope 'Application.ReadWrite.All' 6 | 7 | #Get the current date 8 | $currentDate = Get-Date 9 | 10 | #Get all app registrations 11 | $appRegistrations = Get-MgApplication -All 12 | 13 | #Create an array to store the output 14 | $output = @() 15 | 16 | #Loop through each app registration 17 | foreach ($app in $appRegistrations) { 18 | #Get all secrets for the app registration 19 | $secrets = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/applications/$($app.Id)/passwordCredentials" 20 | 21 | #Loop through each secret 22 | foreach ($secret in $secrets.Value) { 23 | #Check if endDateTime is not null 24 | if ($null -ne $secret.endDateTime) { 25 | #Calculate the number of days until the secret expires 26 | $daysUntilExpiry = ($secret.endDateTime - $currentDate).Days 27 | 28 | #Check if the secret expires in the next 10 days 29 | if ($daysUntilExpiry -le 10) { 30 | #Add the app registration and secret details to the output array 31 | $output += New-Object PSObject -Property @{ 32 | "App Name" = $app.DisplayName 33 | "Secret KeyId" = $secret.KeyId 34 | "Days Until Expiry" = $daysUntilExpiry 35 | } 36 | } 37 | } 38 | } 39 | } 40 | 41 | #Sort the output by the "Days Until Expiry" property and output in a table format 42 | $output | Sort-Object "Days Until Expiry" -Descending | Format-Table 43 | 44 | ################################ 45 | #Export the output to a CSV file 46 | ################################ 47 | 48 | #Get the current date 49 | $currentDate = Get-Date 50 | 51 | #Get all app registrations 52 | $appRegistrations = Get-MgApplication -All 53 | 54 | #Create an array to store the output 55 | $output = @() 56 | 57 | #Loop through each app registration 58 | foreach ($app in $appRegistrations) { 59 | #Get all secrets for the app registration 60 | $secrets = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/applications/$($app.Id)/passwordCredentials" 61 | 62 | #Loop through each secret 63 | foreach ($secret in $secrets.Value) { 64 | #Check if endDateTime is not null 65 | if ($null -ne $secret.endDateTime) { 66 | #Calculate the number of days until the secret expires 67 | $daysUntilExpiry = ($secret.endDateTime - $currentDate).Days 68 | 69 | #Check if the secret expires in the next 10 days 70 | if ($daysUntilExpiry -le 10) { 71 | #Add the app registration and secret details to the output array 72 | $output += New-Object PSObject -Property @{ 73 | "App Name" = $app.DisplayName 74 | "Secret KeyId" = $secret.KeyId 75 | "Days Until Expiry" = $daysUntilExpiry 76 | } 77 | } 78 | } 79 | } 80 | } 81 | 82 | #Export the output array to a CSV file 83 | $output | Export-Csv -Path "ExpiringSecrets.csv" -NoTypeInformation -------------------------------------------------------------------------------- /Entra_ID/Investigate_compromised_enterprise_app.ps1: -------------------------------------------------------------------------------- 1 | #Install the Microsoft Graph PowerShell SDK module 2 | Install-Module Microsoft.Graph -Verbose -AllowClobber -Force 3 | 4 | #Authenticate with your Entra ID account 5 | Connect-MgGraph -Scope 'Application.ReadWrite.All' 6 | 7 | #Get all applications 8 | $applications = Get-MgApplication -All 9 | 10 | #Create an array to store the output 11 | $output = @() 12 | 13 | #Loop through each application 14 | foreach ($app in $applications) { 15 | #Get the service principal for the application 16 | $servicePrincipal = Get-MgServicePrincipal -Filter "appId eq '$($app.AppId)'" 17 | 18 | #Add the application name and service principal ObjectId to the output array 19 | $output += New-Object PSObject -Property @{ 20 | "App Name" = $app.DisplayName 21 | "ObjectId" = $servicePrincipal.Id 22 | } 23 | } 24 | 25 | #Output the array in a table format 26 | $output | Format-Table 27 | 28 | ############################################# 29 | #Remove all users assigned to the application 30 | ############################################# 31 | 32 | #Get Service Principal using objectId 33 | $sp = Get-MgServicePrincipal -ServicePrincipalId 46ddcaa9-ef22-42cb-b569-50df47cea6e1 34 | 35 | #Get MS Graph App role assignments using objectId of the Service Principal 36 | $assignments = Get-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $sp.Id -All 37 | 38 | $assignments | Select-Object PrincipalDisplayName 39 | 40 | #Remove all users and groups assigned to the application 41 | $assignments | ForEach-Object { 42 | if ($_.PrincipalType -eq "User") { 43 | Remove-MgUserAppRoleAssignment -UserId $_.PrincipalId -AppRoleAssignmentId $_.Id 44 | } elseif ($_.PrincipalType -eq "Group") { 45 | Remove-MgGroupAppRoleAssignment -GroupId $_.PrincipalId -AppRoleAssignmentId $_.Id 46 | } 47 | } 48 | 49 | #################################### 50 | #Revoke refresh tokens for all users 51 | #################################### 52 | 53 | #Get Service Principal using objectId 54 | $sp = Get-MgServicePrincipal -ServicePrincipalId 46ddcaa9-ef22-42cb-b569-50df47cea6e1 55 | 56 | #Get MS Graph App role assignments using objectId of the Service Principal 57 | $assignments = Get-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $sp.Id -All | Where-Object {$_.PrincipalType -eq "User"} 58 | 59 | $assignments | Format-List 60 | 61 | #Revoke refresh token for all users assigned to the application 62 | $assignments | ForEach-Object { 63 | Invoke-MgInvalidateUserRefreshToken -UserId $_.PrincipalId 64 | } 65 | 66 | ################################################## 67 | #Revoke all permissions granted to the application 68 | ################################################## 69 | 70 | #Get Service Principal using objectId 71 | $sp = Get-MgServicePrincipal -ServicePrincipalId 46ddcaa9-ef22-42cb-b569-50df47cea6e1 72 | 73 | #Get all delegated permissions for the service principal 74 | $spOAuth2PermissionsGrants = Get-MgServicePrincipalOauth2PermissionGrant -ServicePrincipalId $sp.Id -All 75 | 76 | #Remove all delegated permissions 77 | $spOAuth2PermissionsGrants | ForEach-Object { 78 | Remove-MgOauth2PermissionGrant -OAuth2PermissionGrantId $_.Id 79 | } 80 | 81 | #Get all application permissions for the service principal 82 | $spApplicationPermissions = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id 83 | 84 | #Remove all app role assignments 85 | $spApplicationPermissions | ForEach-Object { 86 | Remove-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $_.PrincipalId -AppRoleAssignmentId $_.Id 87 | } -------------------------------------------------------------------------------- /Intune/Intune_device_management_logs.ps1: -------------------------------------------------------------------------------- 1 | #To make some space below 2 | Set-Location C:\ 3 | Clear-Host 4 | 5 | #Istall the module. (You need admin on the machine.) 6 | Install-Module Microsoft.Graph -AllowClobber -Verbose -Force 7 | 8 | #Search for specific cmdlets 9 | get-command *get-mgdevice* 10 | 11 | #Set the variable with the tenant ID 12 | $TenantID = "your Tenant ID" 13 | 14 | #Connect to the graph 15 | Connect-MgGraph -TenantId $TenantID -Scopes "AuditLog.Read.All","Directory.Read.All" 16 | 17 | #Get a list of all devices 18 | Get-MgDevice -All 19 | 20 | #Get-Member to see the properties 21 | Get-MgDevice | Get-Member 22 | 23 | #Get a list of all devices and select the properties 24 | Get-MgDevice -All | Select-Object DisplayName, EnrollmentProfileName, ApproximateLastSignInDateTime, DeviceId 25 | 26 | #Get Infos about a specific device 27 | Get-MgDeviceByDeviceId -DeviceId 88069fe5-367d-4cbd-be38-1c7b73740fcd | Select-Object * 28 | 29 | #Add more permissions to the connection 30 | Connect-MgGraph -TenantId $TenantID -Scopes "AuditLog.Read.All","Directory.Read.All", "DeviceManagementApps.Read.All", "DeviceManagementApps.ReadWrite.All" 31 | 32 | #Get a list of the Audit events 33 | Get-MgDeviceManagementAuditEvent 34 | 35 | #Get a list of the Audit events and select the properties 36 | Get-MgDeviceManagementAuditEvent | Select-Object Category, ActivityDateTime, ActivityResult, ComponentName, Id | Format-Table -AutoSize 37 | 38 | #Get all detected apps 39 | $detectedApps = Get-MgDeviceManagementDetectedApp 40 | 41 | #Output detected apps 42 | Write-Output "Detected Apps:" $detectedApps 43 | 44 | #Get all device compliance policies 45 | $deviceCompliancePolicies = Get-MgDeviceManagementDeviceCompliancePolicy 46 | 47 | #Output device compliance policies 48 | Write-Output "Device Compliance Policies:" $deviceCompliancePolicies 49 | 50 | #Get all IoT update statuses 51 | $ioUpdateStatuses = Get-MgDeviceManagementIoUpdateStatus 52 | 53 | #Output IoT update statuses 54 | Write-Output "IoT Update Statuses:" $ioUpdateStatuses 55 | 56 | #Get all managed devices 57 | $managedDevices = Get-MgDeviceManagementManagedDevice 58 | 59 | #Output managed devices 60 | Write-Output "Managed Devices:" $managedDevices 61 | 62 | #Get all managed device overviews 63 | $managedDeviceOverviews = Get-MgDeviceManagementManagedDeviceOverview 64 | 65 | #Output managed device overviews 66 | Write-Output "Managed Device Overviews:" $managedDeviceOverviews 67 | 68 | #Add more permissions to the connection 69 | Connect-MgGraph -TenantId $TenantID -Scopes "AuditLog.Read.All","Directory.Read.All", "DeviceManagementApps.Read.All", "DeviceManagementApps.ReadWrite.All", "DeviceManagementRBAC.Read.All", "DeviceManagementRBAC.ReadWrite.All" 70 | 71 | #Get all resource operations 72 | $resourceOperations = Get-MgDeviceManagementResourceOperation 73 | 74 | #Output resource operations 75 | Write-Output "Resource Operations:" $resourceOperations 76 | 77 | #Get all role definitions 78 | $roleDefinitions = Get-MgDeviceManagementRoleDefinition 79 | 80 | #Output role definitions 81 | $roleDefinitions | Select-Object DisplayName, Description 82 | 83 | #Get all managed app policies 84 | $managedAppPolicies = Get-MgDeviceAppManagementManagedAppPolicy 85 | 86 | #Output managed app policies 87 | Write-Output "Managed App Policies:" $managedAppPolicies 88 | 89 | #Get Device Maangement Configuration 90 | Get-MgDeviceManagementDeviceConfiguration 91 | 92 | Get-MgDeviceManagementDeviceConfiguration -Filter "startswith(DisplayName,'Config')" | Select-Object DisplayName,Id 93 | 94 | Get-MgDeviceManagementDeviceConfiguration -Filter "startswith(DisplayName,'Config')" | Select-Object DisplayName,Id | Out-GridView -------------------------------------------------------------------------------- /Intune/Intune_Audit_logs.ps1: -------------------------------------------------------------------------------- 1 | #To make some space below 2 | Set-Location C:\ 3 | Clear-Host 4 | 5 | #Istall the module. (You need admin on the machine.) 6 | Install-Module Microsoft.Graph -AllowClobber -Verbose -Force 7 | 8 | #Search for specific cmdlets 9 | get-command *-mgaudit* 10 | 11 | #Set the variable with the tenant ID 12 | $TenantID = "your Tenant ID" 13 | 14 | #Connect to the graph 15 | Connect-MgGraph -TenantId $TenantID -Scopes "AuditLog.Read.All","Directory.Read.All" 16 | 17 | #Get ApplicationManagemnt logs 18 | Get-MgAuditLogDirectoryAudit -Filter "category eq 'ApplicationManagement'" 19 | 20 | #Get all device logs 21 | Get-MgAuditLogDirectoryAudit -Filter "category eq 'Device'" 22 | 23 | #Get all device logs in the past 30 days. Date must be properly formatted 24 | [dateTime]$Past30Days = (get-date).addDays(-30) 25 | $Past30DaysFormatted = Get-Date $Past30Days -Format yyyy-MM-dd 26 | Get-MgAuditLogDirectoryAudit -Filter "category eq 'Device' and activityDateTime gt $Past30DaysFormatted" 27 | 28 | #All actions initiated by Intune 29 | Get-MgAuditLogDirectoryAudit -Filter "initiatedBy/app/displayName eq 'Microsoft Intune'" | Select-Object activitydisplayname,@{Name = 'Devicename'; Expression = {$_.targetresources.displayname}},result,resultreason 30 | 31 | #Get failed actions 32 | Get-MgAuditLogDirectoryAudit -Filter "result eq 'Failure'" | 33 | Select-Object activitydisplayname,@{Name = 'Devicename'; Expression = {$_.targetresources.displayname}},result,resultreason 34 | 35 | #Get failed device creation 36 | Get-MgAuditLogDirectoryAudit -Filter "activitydisplayname eq 'Add device' and result eq 'Failure'" 37 | 38 | #Why did the device creation fail? 39 | Get-MgAuditLogDirectoryAudit -Filter "activitydisplayname eq 'Add device' and result eq 'Failure'" | 40 | Select-Object activitydisplayname,@{Name = 'Devicename'; Expression = {$_.targetresources.displayname}},result,resultreason 41 | 42 | #The last login 43 | Get-MgAuditLogSignIn -Top 1 | Format-List 44 | 45 | #About a user 46 | Get-MgAuditLogSignIn -Filter "UserPrincipalName eq 'name@example.com'" 47 | 48 | $Logs = Get-MgAuditLogSignIn -Filter "startsWith(userDisplayName,'James')" -All 49 | $Logs | Group-Object -Property AppDisplayName | Select-Object -Property Name,Count | Sort-Object -Property Count -Descending 50 | 51 | #Filter logs based on the AppDisplayName 52 | $Logs = $Logs | Where-Object {$PSITEM.AppDisplayName -eq "Windows Sign In"} 53 | $Logs 54 | 55 | $Logs = Get-MgAuditLogSignIn -Filter "startsWith(userDisplayName,'James')" -All 56 | $Logs | Select-Object -Property AppDisplayName -Unique 57 | 58 | #Sort sign-in logs based on the CreatedDateTime 59 | $Logs = Get-MgAuditLogSignIn -Filter "startsWith(userDisplayName,'James')" -Top 10 60 | $Logs | Sort-Object -Property CreatedDateTime | Select-Object -Property AppDisplayName,CreatedDateTime,UserDisplayName 61 | 62 | #The applications used 63 | $signin = Get-MgAuditLogSignIn -Top 1000 64 | $signin | Group-Object AppDisplayName -NoElement 65 | 66 | #Retrieval of the "Basic Auth" logins of the last 30 days 67 | $startdate = (get-date).adddays(-30) 68 | $sstartdate = $startdate.ToString("yyy-MM-dd") 69 | $basicsignin = Get-MgAuditLogSignIn -Filter "CreatedDateTime ge $sstartdate and ClientAppUsed ne 'Browser' and ClientAppUsed ne 'Mobile Apps and Desktop clients' and ClientAppUsed ne ''" 70 | $basicsignin | Group-Object ClientAppUsed -NoElement 71 | 72 | #Find Permissions 73 | Find-MgGraphCommand -Uri '/security/alerts' 74 | Find-MgGraphCommand -Command 'Get-MgSecurityAlert' | Select-Object Permissions 75 | 76 | #Create a new connection 77 | Disconnect-Graph 78 | Connect-MgGraph -Scopes SecurityEvents.Read.All, SecurityEvents.ReadWrite.All 79 | 80 | #Examine the Security Alerts 81 | Get-MgSecurityAlert 82 | 83 | #A bit 84 | Get-MgSecurityAlert | Select-Object Title, Description, Category, Id | Out-GridView 85 | 86 | #More detailed info 87 | Get-MgSecurityAlert -AlertId e208bab9f9b02156e737c42d190e60d6bd5c49a7cc51a0432169973753f8503d 88 | 89 | #List content from an alert ID 90 | Get-MgSecurityAlert -AlertId e208bab9f9b02156e737c42d190e60d6bd5c49a7cc51a0432169973753f8503d | Select-Object * -------------------------------------------------------------------------------- /Entra_ID/Managing_Users_Groups.ps1: -------------------------------------------------------------------------------- 1 | Set-Location C:\ 2 | Clear-Host 3 | 4 | #If needed 5 | Import-Module Microsoft.Graph 6 | 7 | #Install into the Current User Scope 8 | Install-Module Microsoft.Graph -Scope CurrentUser -AllowClobber -Verbose -Force 9 | 10 | #Connect for User Management: 11 | 12 | #Read Only Connection 13 | $scopes = @( 14 | "User.ReadBasic.All" 15 | "User.Read.All" 16 | "Directory.Read.All" 17 | ) 18 | Connect-MgGraph -Scopes $scopes 19 | 20 | #Read and Write Connection 21 | $scopes = @( 22 | "User.ReadWrite.All" 23 | "Directory.ReadWrite.All" 24 | ) 25 | Connect-MgGraph -Scopes $scopes 26 | 27 | #Check the permissions 28 | Get-MgContext | Select-Object -ExpandProperty scopes 29 | 30 | #Retrieving User Accounts: 31 | 32 | #Retrieve All Users 33 | Get-MgUser | Format-List ID, DisplayName, Mail, UserPrincipalName 34 | 35 | #Retrieve Specific User by ID 36 | Get-MgUser -UserId 'e08d23a7-b6db-4d19-919d-baffc82949ef' | Format-List ID, DisplayName, Mail, UserPrincipalName 37 | 38 | #Create a New User Account 39 | $password = @{ Password= 'P@ssw0rd4625???' } 40 | New-MgUser -DisplayName 'Timo Jones' -PasswordProfile $password -AccountEnabled -MailNickName 'timojones' -UserPrincipalName 'timo.jones@tomsazure.ch' 41 | 42 | #Updating User Accounts 43 | 44 | #Update User Using ID 45 | Update-MgUser -UserId '8ffd0594-0b5f-4355-ba5f-50f7b1b614a2' -DisplayName 'Timo R Jones' 46 | 47 | #Did it work 48 | Get-MgUser -UserId '8ffd0594-0b5f-4355-ba5f-50f7b1b614a2' 49 | 50 | #Retrieve User Using Filtering, Then Update 51 | $user = Get-MgUser -ConsistencyLevel eventual -Filter "startsWith(UserPrincipalName, 'timo.jones@tomsazure.ch')" 52 | Update-MgUser -UserId $user.Id -DisplayName 'Timo Jones' 53 | 54 | #Did it work 55 | Get-MgUser -UserId '8ffd0594-0b5f-4355-ba5f-50f7b1b614a2' 56 | 57 | #Deleting User Accounts 58 | 59 | #Remove User by ID 60 | Remove-MgUser -UserId '8ffd0594-0b5f-4355-ba5f-50f7b1b614a2' 61 | 62 | #Remove User by ID with Confirmation 63 | Remove-MgUser -UserId '8ffd0594-0b5f-4355-ba5f-50f7b1b614a2' -Confirm 64 | 65 | #Retrieve User Using Filtering, Then Delete 66 | $user = Get-MgUser -ConsistencyLevel eventual -Filter "startsWith(UserPrincipalName, 'timo.jones@tomsazure.ch')" 67 | Remove-MgUser -UserId $user.Id -Confirm 68 | 69 | #Did it work 70 | Get-MgUser -UserId '8ffd0594-0b5f-4355-ba5f-50f7b1b614a2' 71 | 72 | #Connect for Group Management: 73 | 74 | #Read Only Connection 75 | $scopes = @("Group.Read.All") 76 | Connect-MgGraph -Scopes $scopes 77 | 78 | #Read and Write Connection 79 | $scopes = @("Group.ReadWrite.All") 80 | Connect-MgGraph -Scopes $scopes 81 | 82 | #Read and Write Connection Including Group Memberships 83 | $scopes = @( 84 | "Group.ReadWrite.All" 85 | "GroupMember.ReadWrite.All") 86 | Connect-MgGraph -Scopes $scopes 87 | 88 | #Check the permissions 89 | Get-MgContext | Select-Object -ExpandProperty scopes 90 | 91 | #Retrieving Groups: 92 | 93 | #Retrieve All Groups 94 | Get-MgGroup | Format-List ID, DisplayName, Description, GroupTypes 95 | 96 | #Retrieve Specific Group by ID 97 | Get-MgGroup -GroupId '12eda8b0-695b-4f57-a7b3-245b2a6552c9' | Format-List ID, DisplayName, Description, GroupTypes 98 | 99 | #Retrieve Groups by Filtering 100 | Get-MgGroup -ConsistencyLevel eventual -Filter "startsWith(DisplayName, 'Technik')" 101 | 102 | #Creating Groups: 103 | 104 | #Create a New Group 105 | New-MgGroup -DisplayName 'MSGraph' -MailEnabled: $False -MailNickName 'MSGraph' -SecurityEnabled 106 | 107 | #Updating Groups: 108 | 109 | #Update Group Using ID 110 | $properties = @{ 111 | "Description" = "New MS Graph Group" 112 | "DisplayName" = "New MS Graph Group Description" 113 | } 114 | Update-MgGroup -GroupId 'b2af405b-1c46-46c2-be8e-5288bc9c7dc6' -BodyParameter $properties 115 | 116 | #Did it work? 117 | Get-MgGroup -GroupId 'b2af405b-1c46-46c2-be8e-5288bc9c7dc6' 118 | 119 | #Deleting Groups: 120 | 121 | #Remove Group by ID 122 | Remove-MgGroup -GroupId 'b2af405b-1c46-46c2-be8e-5288bc9c7dc6' 123 | 124 | #Remove Group by ID with Confirmation 125 | Remove-MgGroup -GroupId 'b2af405b-1c46-46c2-be8e-5288bc9c7dc6' -Confirm 126 | 127 | #Retrieve Group Using Filtering, Then Delete 128 | $group = Get-MgGroup -ConsistencyLevel eventual -Filter "startsWith(DisplayName, 'New MS Graph Group Description')" 129 | Remove-MgGroup -GroupId $group.Id -Confirm 130 | 131 | #Did it work? 132 | Get-MgGroup -GroupId 'b2af405b-1c46-46c2-be8e-5288bc9c7dc6' 133 | 134 | #Modify Group Membership: 135 | 136 | #Add a Group Member 137 | $user = Get-MgUser -ConsistencyLevel eventual -Search '"DisplayName:Timo Meyer"' 138 | $group = Get-MgGroup -GroupId 'be278623-1c0b-4c18-bb97-c617463ca920' 139 | 140 | New-MgGroupMember -GroupId $group.Id -DirectoryObjectId $user.Id 141 | 142 | #Did work? 143 | Get-MgGroupMember -GroupId $group.Id -------------------------------------------------------------------------------- /Learning_Tutorials/01_Graph_explorer_and_powershell.md: -------------------------------------------------------------------------------- 1 | # Get to know the Microsoft Graph PowerShell SDK better with the Graph Explorer. 2 | 3 | Before we get started, what exactly are we talking about? Working with the Microsoft Graph PowerShell SDK can be a bit of a challenge. Installing the PowerShell module may still work, but then the first challenges arise. For example, which authorizations/scopes do I need to be able to complete the task? Delegated or application authorizations? Two questions that can very quickly (often negatively ;-) affect motivation. 4 | 5 | In this tutorial we will take a closer look at the Graph Explorer. The Graph Explorer is a web application that allows you to interactively query the Microsoft Graph. The Graph Explorer is a great way to get to know the Microsoft Graph and the PowerShell SDK. In addition, the Graph Explorer is a great tool for troubleshooting and debugging. 6 | 7 | ## Prerequisites 8 | 9 | - Microsoft 365 Developer Tenant 10 | - Microsoft Graph PowerShell SDK 11 | - Microsoft Graph Explorer 12 | 13 | ## Step by step 14 | 15 | So that you can test the Microsoft Graph PowerShell SDK without risk, I recommend that you set up a free Microsoft 365 Developer Tenant. As just mentioned, this is free of charge and no credit card is required. 16 | You can create a test environment using the following link: 17 | https://developer.microsoft.com/en-us/microsoft-365/dev-program 18 | 19 | After you have created your test environment, you can install the Microsoft Graph PowerShell SDK. You can find the installation instructions here: 20 | [Link to the PowerShell File](../Installing_Microsoft_Graph_PowerShell_SDK.ps1) 21 | 22 | After you have installed the Microsoft Graph PowerShell SDK, you can start the Graph Explorer. You can find the Graph Explorer here: 23 | aka.ms/ge 24 | or 25 | https://developer.microsoft.com/en-us/graph/graph-explorer 26 | 27 | The Graph Explorer 28 | 29 | > Note: You can set up a free Microsoft 365 Developer Tenant directly from Graph Explorer (if not already done - red arrow). 30 | 31 | **You can then log in (see red square at the top of the picture).** 32 | 33 | log in 34 | 35 | **Now you must give your consent.** 36 | 37 | consent 38 | 39 | **Now we are registered!** 40 | 41 | registered 42 | 43 | **But what exactly happened in the background when we gave the consent (we remember the consent was not for the entire organization). We can find the answer in the Entra Admin Center.** 44 | 45 | In the Entra ID 46 | 47 | **We see the authorizations granted for the Graph Explorer Enterprise Application.** 48 | 49 | The permissions 50 | 51 | > Note: Delegated Microsoft Graph permissions refer to permissions granted by a user to a application to access their Microsoft Graph data on their behalf. This means that the application acts on behalf of a logged-in user. However, the application can never access anything that the logged-in user could not access. 52 | On the other hand, application permissions are permissions granted to an application itself to access Microsoft Graph data without a user context¹. This means that the app accesses Microsoft Graph with its own identity without a logged-in user. 53 | 54 | But now we come back to the actual topic. How can the Graph Explorer help us to get to know the Microsoft Graph PowerShell SDK better? Let's start with a simple example, listing the groups in our organization. Take a look at all the valuable information the Graph Explorer can provide us with (We can also see that we do not yet have the necessary authorizations.). We get information about the necessary permissions (always start with the fewest permissions - it doesn't always need all of them - as we'll see in a moment). 55 | 56 | **The Graph Explorer shows us the necessary permissions.** 57 | 58 | The permissions 59 | 60 | **Only give your consent for one authorization and start the query again.** 61 | 62 | Run query again 63 | 64 | **The query was now successful.** 65 | 66 | The query 67 | 68 | > Note: By the way, at the arrow at the top - click on the symbol and you will receive information about this query. 69 | 70 | **Let us now apply all this knowledge directly. We can now apply what we have learned in Visual Studio Code.** 71 | 72 | In Visual Studio Code 73 | 74 | I am fully aware that this is not a complete tutorial covering everything that Graph Explorer and the Microsoft PowerShell SDK has to offer. Nevertheless, I hope that this provides you with a good starting point and I thank you for reading the article. 75 | 76 | --- 77 | ## *HAPPY GRAPHING!* 78 | --- -------------------------------------------------------------------------------- /Microsoft_365/Office_365_Management_API/Investigate_logs.ps1: -------------------------------------------------------------------------------- 1 | #https://learn.microsoft.com/en-us/office/office-365-management-api/get-started-with-office-365-management-apis 2 | 3 | #First create an Azure App Registration in the Entra Admin Center 4 | #For the investigation we need an Azure App Registration with the following permissions: 5 | #Office 365 Management APIs > ActivityFeed.Read 6 | #Office 365 Management APIs > ActivityFeed.ReadDlp 7 | #Office 365 Management APIs > ServiceHealth.Read (Optinal) 8 | 9 | #Do not forget to grant admin consent for the permissions 10 | 11 | #Set Variables 12 | $ClientID = "" 13 | $ClientSecret = "" 14 | $tenantdomain = ".onmicrosoft.com" 15 | $TenantGUID = "" 16 | $loginURL = "https://login.microsoftonline.com/" 17 | $resource = "https://manage.office.com" 18 | 19 | $body = @{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret} 20 | $oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body $body 21 | $headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"} 22 | 23 | #Get Subscription Status 24 | Invoke-WebRequest -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/list" 25 | 26 | #Start Subscriptions 27 | Invoke-WebRequest -Method Post -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/start?contentType=Audit.AzureActiveDirectory" 28 | 29 | Invoke-WebRequest -Method Post -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/start?contentType=Audit.SharePoint" 30 | 31 | Invoke-WebRequest -Method Post -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/start?contentType=Audit.General" 32 | 33 | Invoke-WebRequest -Method Post -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/start?contentType=Audit.Exchange" 34 | 35 | ########## 36 | #EXAMPLE 1 37 | ########## 38 | 39 | #Retrieve Items from Audit.AzurectiveDirectory 40 | Invoke-WebRequest -Method GET -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/content?contentType=Audit.AzureActiveDirectory" 41 | 42 | #Perform a Date Range Query 43 | $startTimeDt = "2023-10-02T05:00:00.000Z" 44 | $endTimeDt = "2023-10-02T21:00:10.123Z" 45 | 46 | $response = Invoke-WebRequest -Method GET -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/content?startTime=$startTimeDt&endTime=$endTimeDt&contentType=Audit.AzureActiveDirectory&PublisherIdentifier=$TenantGUID" 47 | 48 | #View Response 49 | $response | Select-Object -ExpandProperty Content 50 | 51 | #Loop All Items and View Actual Records 52 | $contentResult = $response.Content | ConvertFrom-Json 53 | foreach ($contentItem in $contentResult) { 54 | $blobUri = $contentItem.contentUri 55 | try { 56 | $blobResponse = Invoke-WebRequest -Method Get -Headers $headerParams -Uri $blobUri 57 | $results = $blobResponse.Content | ConvertFrom-Json 58 | Write-Output $results 59 | } 60 | catch { 61 | Write-Error $_.Exception.Message 62 | } 63 | } 64 | 65 | #List specific properties 66 | $contentResult = $response.Content | ConvertFrom-Json 67 | $table = @() 68 | foreach ($contentItem in $contentResult) { 69 | $blobUri = $contentItem.contentUri 70 | try { 71 | $blobResponse = Invoke-WebRequest -Method Get -Headers $headerParams -Uri $blobUri 72 | $results = $blobResponse.Content | ConvertFrom-Json 73 | foreach ($result in $results) { 74 | $operation = $result.Operation 75 | $userID = $result.UserID 76 | $actorIPAddress = $result.ActorIPAddress 77 | $table += [pscustomobject]@{ 78 | Operation = $operation 79 | UserID = $userID 80 | ActorIPAddress = $actorIPAddress 81 | } 82 | } 83 | } 84 | catch { 85 | Write-Error $_.Exception.Message 86 | } 87 | } 88 | $table | Format-Table 89 | 90 | ########## 91 | #EXAMPLE 2 92 | ########## 93 | 94 | # Replace these values with your own 95 | $ClientID = "" 96 | $ClientSecret = "" 97 | $tenantdomain = ".onmicrosoft.com" 98 | $TenantGUID = "" 99 | $loginURL = "https://login.microsoftonline.com/" 100 | $resource = "https://manage.office.com" 101 | 102 | $body = @{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret} 103 | $oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body $body 104 | $headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"} 105 | 106 | #Retrieve Items from Audit.SharePoint 107 | Invoke-WebRequest -Method GET -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/content?contentType=Audit.General" 108 | 109 | #Perform a Date Range Query 110 | $startTimeDt = "2023-10-03T05:00:00.000Z" 111 | $endTimeDt = "2023-10-03T21:00:10.123Z" 112 | 113 | $response = Invoke-WebRequest -Method GET -Headers $headerParams -Uri "$resource/api/v1.0/$tenantGUID/activity/feed/subscriptions/content?startTime=$startTimeDt&endTime=$endTimeDt&contentType=Audit.General&PublisherIdentifier=$TenantGUID" 114 | 115 | #View Response 116 | $response | Select-Object -ExpandProperty Content 117 | 118 | #Loop All Items and View Actual Records 119 | $contentResult = $response.Content | ConvertFrom-Json 120 | foreach ($contentItem in $contentResult) { 121 | $blobUri = $contentItem.contentUri 122 | try { 123 | $blobResponse = Invoke-WebRequest -Method Get -Headers $headerParams -Uri $blobUri 124 | $results = $blobResponse.Content | ConvertFrom-Json 125 | Write-Output $results 126 | } 127 | catch { 128 | Write-Error $_.Exception.Message 129 | } 130 | } 131 | 132 | #List specific properties 133 | $contentResult = $response.Content | ConvertFrom-Json 134 | foreach ($contentItem in $contentResult) { 135 | $blobUri = $contentItem.contentUri 136 | try { 137 | $blobResponse = Invoke-WebRequest -Method Get -Headers $headerParams -Uri $blobUri 138 | $results = $blobResponse.Content | ConvertFrom-Json | Select-Object CreationTime, Workload, ResultStatus 139 | $results | Format-Table 140 | } 141 | catch { 142 | Write-Error $_.Exception.Message 143 | } 144 | } --------------------------------------------------------------------------------