← cd ~/tools
Save time
Script library
All 74 scripts and queries from the posts on this site, in one place. Search by what you want to do, filter by language and copy. Each one links back to the post that explains it.
- Free
- Runs in your browser
- No sign-up
-
PowerShell
Connect-MgGraph -Scopes ServiceHealth.Read.All Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues/EX1550543"What each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Calls the Microsoft Graph API directly.
-
Today: the one-hour checkFive Microsoft products reach end of support tomorrow: the last-day checksPowerShell
Connect-MgGraph -Scopes DeviceManagementManagedDevices.Read.All Get-MgDeviceManagementManagedDevice -Filter "operatingSystem eq 'Windows'" -All | Where-Object OsVersion -like '10.0.22631*' | Select-Object DeviceName, UserPrincipalName, OsVersion, LastSyncDateTime | Export-Csv .\windows-11-23h2-devices.csv -NoTypeInformationWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Reads device management managed device details from Microsoft Graph.
- Line 3: Keeps only the items that match the condition.
- Line 4: Keeps only the properties listed, so the output stays small.
- Line 5: Saves the results as a CSV file you can open in Excel.
-
PowerShell
Resolve-DnsName -Type TXT _dmarc.contoso.com | Select-Object -ExpandProperty StringsWhat each line does
- Line 1: Looks up DNS records for a name.
-
CLI / shell
nslookup -type=TXT _dmarc.contoso.com -
The wsb command line (Windows 11 24H2)Windows Sandbox for IT admins: test apps and suspicious files in a throwaway WindowsPowerShell
wsb start # returns the new sandbox's ID $id = "12345678-1234-1234-1234-1234567890AB" # paste the ID here wsb share --id $id -f C:\Packaging\ContosoAgent -s C:\Package wsb connect --id $id wsb exec --id $id -c "msiexec /i C:\Package\ContosoAgent.msi /qn /norestart" -r System wsb stop --id $id -
Find what you still haveAzure web role vs worker role: what they were, and where to move them before March 2027KQL
az graph query -q "resources | where type =~ 'microsoft.compute/cloudservices' | project name, resourceGroup, subscriptionId, location" -o table -
Find who has the big rolesAzure built-in roles explained: Owner, Contributor, Reader and what to use insteadPowerShell
Connect-AzAccount $sub = "/subscriptions/00000000-0000-0000-0000-000000000000" foreach ($role in "Owner", "User Access Administrator", "Role Based Access Control Administrator") { Get-AzRoleAssignment -Scope $sub -RoleDefinitionName $role | Select-Object @{ n = "Role"; e = { $role } }, DisplayName, SignInName, ObjectType, Scope }What each line does
- Line 1: Signs in to Azure.
- Line 4: Reads role assignment details from Azure.
- Line 5: Keeps only the properties listed, so the output stays small.
-
Find who has the big rolesAzure built-in roles explained: Owner, Contributor, Reader and what to use insteadCLI / shell
az role assignment list --all --role Owner --include-inherited \ --query "[].{who:principalName, type:principalType, scope:scope}" -o tableWhat each line does
- Line 1: Azure CLI: lists role assignments.
-
Find the apps with the most accessMicrosoft Graph permissions explained: delegated vs application, consent and least privilegePowerShell
Connect-MgGraph -Scopes "Application.Read.All" $graph = Get-MgServicePrincipal -Filter "appId eq '00000003-0000-0000-c000-000000000000'" $names = @{}; $graph.AppRoles | ForEach-Object { $names[$_.Id] = $_.Value } Get-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $graph.Id -All | Select-Object PrincipalDisplayName, @{ n = "Permission"; e = { $names[$_.AppRoleId] } } | Sort-Object Permission, PrincipalDisplayNameWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Reads service principal details from Microsoft Graph.
- Line 3: Runs the block once for each item coming down the pipeline.
- Line 4: Reads service principal app role assigned to details from Microsoft Graph.
- Line 5: Keeps only the properties listed, so the output stays small.
- Line 6: Sorts the results.
-
Entra ID: what Microsoft keeps for youEntra ID and Active Directory backup and recovery: the complete guidePowerShell
Connect-MgGraph -Scopes "User.ReadWrite.All" # List soft-deleted users Get-MgDirectoryDeletedItemAsUser -All | Select-Object Id, DisplayName, UserPrincipalName, DeletedDateTime # Restore one by its ID Restore-MgDirectoryDeletedItem -DirectoryObjectId "<object id>"What each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 3: Reads directory deleted item as user details from Microsoft Graph.
- Line 4: Keeps only the properties listed, so the output stays small.
- Line 6: Restores a directory deleted item in Microsoft Graph. Makes a change.
-
Entra ID: what Microsoft keeps for youEntra ID and Active Directory backup and recovery: the complete guidePowerShell
Connect-MgGraph -Scopes "Policy.Read.All" $out = "CA-export-$(Get-Date -Format yyyy-MM-dd)" New-Item -ItemType Directory -Path $out | Out-Null Get-MgIdentityConditionalAccessPolicy -All | ForEach-Object { $_ | ConvertTo-Json -Depth 10 | Out-File "$out\$($_.DisplayName -replace '[\\/:*?"<>|]', '_').json" }What each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Gets the current date and time.
- Line 3: Creates an item. Makes a change.
- Line 4: Reads identity conditional access policy details from Microsoft Graph.
- Line 5: Turns the results into JSON text.
-
.NET 8 and .NET 910 November is the biggest end-of-support day of the year: what ends, how to find it, and what to move toKQL
resources | where type =~ "microsoft.web/sites" or type =~ "microsoft.web/sites/slots" | mv-expand p = properties.siteProperties.properties | where tostring(p.name) =~ "LinuxFxVersion" | extend stack = tostring(p.value) | where stack matches regex @"(?i)^dotnet(core|-isolated)?\|(8|9)\.0" | project name, kind, resourceGroup, subscriptionId, stack | order by stack asc -
.NET 8 and .NET 910 November is the biggest end-of-support day of the year: what ends, how to find it, and what to move toPowerShell
Get-AzWebApp | ForEach-Object { $c = (Get-AzWebApp -ResourceGroupName $_.ResourceGroup -Name $_.Name).SiteConfig [pscustomobject]@{ App = $_.Name Group = $_.ResourceGroup Windows = $c.NetFrameworkVersion Linux = $c.LinuxFxVersion } } | Where-Object { $_.Windows -in 'v8.0', 'v9.0' -or $_.Linux -match '^DOTNET.*\|(8|9)\.0' }What each line does
- Line 1: Reads web app details from Azure.
- Line 2: Reads web app details from Azure.
- Line 9: Keeps only the items that match the condition.
-
Windows 11 23H2 Enterprise and Education10 November is the biggest end-of-support day of the year: what ends, how to find it, and what to move toPowerShell
Connect-MgGraph -Scopes DeviceManagementManagedDevices.Read.All Get-MgDeviceManagementManagedDevice -Filter "operatingSystem eq 'Windows'" -All | Where-Object OsVersion -like '10.0.22631*' | Select-Object DeviceName, UserPrincipalName, OsVersion, LastSyncDateTime | Export-Csv .\windows-11-23h2-devices.csv -NoTypeInformationWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Reads device management managed device details from Microsoft Graph.
- Line 3: Keeps only the items that match the condition.
- Line 4: Keeps only the properties listed, so the output stays small.
- Line 5: Saves the results as a CSV file you can open in Excel.
-
Find every PHP app you runThe PHP flaw that took websites offline worldwide: what AI found, and what to do in Azure todayKQL
resources | where type =~ "microsoft.web/sites" or type =~ "microsoft.web/sites/slots" | mv-expand p = properties.siteProperties.properties | where tostring(p.name) =~ "LinuxFxVersion" and tostring(p.value) startswith "PHP|" | project name, resourceGroup, subscriptionId, stack = tostring(p.value) | order by stack asc -
Get the fix sooner with the Latest channelThe PHP flaw that took websites offline worldwide: what AI found, and what to do in Azure todayCLI / shell
az webapp list-runtimes --os linux | grep PHP az webapp config set --resource-group <resource-group> --name <app-name> --slot staging --linux-fx-version "PHP|8.4"What each line does
- Line 3: Azure CLI: changes webapp config. Makes a change.
-
PowerShell
$results = foreach ($sub in Get-AzSubscription) { Set-AzContext -SubscriptionId $sub.Id | Out-Null Get-AzResource -ResourceType "Microsoft.Web/sites" | Where-Object Kind -like "*functionapp*" | ForEach-Object { $site = Get-AzWebApp -ResourceGroupName $_.ResourceGroupName -Name $_.Name $runtime = ($site.SiteConfig.AppSettings | Where-Object Name -eq "FUNCTIONS_WORKER_RUNTIME").Value [pscustomobject]@{ Subscription = $sub.Name App = $_.Name Runtime = $runtime NetVersion = if ($site.SiteConfig.LinuxFxVersion) { $site.SiteConfig.LinuxFxVersion } else { $site.SiteConfig.NetFrameworkVersion } Action = switch ($runtime) { "dotnet" { "Migrate to isolated" } "dotnet-isolated" { "Check .NET version" } default { "Not affected" } } } } } $results | Sort-Object Action, App | Format-Table -AutoSizeWhat each line does
- Line 1: Reads subscription details from Azure.
- Line 2: Changes a context in Azure. Makes a change.
- Line 3: Reads resource details from Azure.
- Line 4: Keeps only the items that match the condition.
- Line 5: Runs the block once for each item coming down the pipeline.
- Line 6: Reads web app details from Azure.
- Line 7: Keeps only the items that match the condition.
- Line 21: Sorts the results.
-
Deploy with no downtimeAzure Functions in-process model ends 10 November 2026: find and migrate your appsCLI / shell
# 1. Point the staging slot at the isolated worker (not as a slot setting) az functionapp config appsettings set -g rg-contoso-orders -n func-contoso-orders --slot staging ` --settings FUNCTIONS_WORKER_RUNTIME=dotnet-isolated # 2. Publish the migrated code to the staging slot and test it # 3. Swap staging into production az functionapp deployment slot swap -g rg-contoso-orders -n func-contoso-orders ` --slot staging --target-slot productionWhat each line does
- Line 2: Azure CLI: changes functionapp config appsettings. Makes a change.
-
Before you start: prerequisitesAzure Arc for servers: the complete setup guideCLI / shell
az account set --subscription "<subscription>" az provider register --namespace Microsoft.HybridCompute az provider register --namespace Microsoft.GuestConfiguration az provider register --namespace Microsoft.HybridConnectivity az provider register --namespace Microsoft.AzureArcData # only for Arc-enabled SQL Server az provider register --namespace Microsoft.Compute # for Update ManagerWhat each line does
- Line 1: Azure CLI: changes your Azure account. Makes a change.
-
After onboarding: switch things onAzure Arc for servers: the complete setup guidePowerShell
$apiVersion = "2020-06-01" $resource = "https://vault.azure.net" $endpoint = "{0}?resource={1}&api-version={2}" -f $env:IDENTITY_ENDPOINT, $resource, $apiVersion try { Invoke-WebRequest -Method GET -Uri $endpoint -Headers @{ Metadata = 'True' } -UseBasicParsing } catch { $secretFile = ($_.Exception.Response.Headers["WWW-Authenticate"] -split "Basic realm=")[1] } $secret = Get-Content -Raw $secretFile $response = Invoke-WebRequest -Method GET -Uri $endpoint -Headers @{ Metadata = 'True'; Authorization = "Basic $secret" } -UseBasicParsing $token = (ConvertFrom-Json $response.Content).access_tokenWhat each line does
- Line 4: Runs web request.
- Line 6: Reads content details.
- Line 7: Runs web request.
- Line 8: Reads JSON text into objects you can work with.
-
Day-two operationsAzure Arc for servers: the complete setup guideKQL
Resources | where type == 'microsoft.hybridcompute/machines' | summarize Servers = count() by Status = tostring(properties.status) -
Day-two operationsAzure Arc for servers: the complete setup guideKQL
AdvisorResources | where type == 'microsoft.advisor/recommendations' | where properties.category == 'HighAvailability' | where properties.shortDescription.solution == 'Upgrade to the latest version of the Azure Connected Machine agent' | project id, JoinId = toupper(properties.resourceMetadata.resourceId), machineName = tostring(properties.impactedValue), agentVersion = tostring(properties.extendedProperties.installedVersion), expectedVersion = tostring(properties.extendedProperties.latestVersion) | join kind=leftouter ( Resources | where type == 'microsoft.hybridcompute/machines' | project machineId = toupper(id), status = tostring(properties.status) ) on $left.JoinId == $right.machineId | where status != 'Expired' | summarize by id, machineName, agentVersion, expectedVersion | order by tolower(machineName) asc -
Check your tenant in one goEvery Entra default user permission, what it does, and how to check yours in one commandPowerShell
Connect-MgGraph -Scopes Policy.Read.All (Get-MgPolicyAuthorizationPolicy).DefaultUserRolePermissions | Format-ListWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Reads authorization policy details from Microsoft Graph.
-
Check your tenant in one goEvery Entra default user permission, what it does, and how to check yours in one commandPowerShell
Connect-MgGraph -Scopes Policy.ReadWrite.Authorization Update-MgPolicyAuthorizationPolicy -DefaultUserRolePermissions @{ AllowedToCreateApps = $false }What each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Updates an authorization policy in Microsoft Graph. Makes a change.
-
The Secure Boot certificatesMicrosoft's deadline week: four products retire tomorrow, and Secure Boot's last 2011 certificate expires next MondayPowerShell
$s = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\SecureBoot\Servicing" -ErrorAction SilentlyContinue [pscustomobject]@{ SecureBootOn = Confirm-SecureBootUEFI Status = $s.UEFICA2023Status Error = $s.UEFICA2023Error CA2023InDb = [Text.Encoding]::ASCII.GetString((Get-SecureBootUEFI db).bytes) -match "Windows UEFI CA 2023" } | Format-ListWhat each line does
- Line 1: Reads item property details.
- Line 6: Reads secure boot uefi details.
- Line 7: Shows every property of each result as a list.
-
Find every one you haveWindows Server 2012 and 2012 R2: the last security update ships tomorrowKQL
DeviceInfo | where Timestamp > ago(7d) | where OSPlatform startswith "WindowsServer2012" | summarize arg_max(Timestamp, OSPlatform, OSBuild, PublicIP) by DeviceName | order by DeviceName asc -
Find every one you haveWindows Server 2012 and 2012 R2: the last security update ships tomorrowKQL
resources | where type in~ ("microsoft.compute/virtualmachines", "microsoft.hybridcompute/machines") | extend os = tostring(coalesce(properties.extended.instanceView.osName, properties.osSku, properties.osName)) | where os has "2012" | project name, type, os, resourceGroup, subscriptionId, location -
Know what agents you haveGoverning AI agent identities in Entra: sponsors, access packages and expiryGraph HTTP
GET https://graph.microsoft.com/beta/auditLogs/signIns?$filter=signInEventTypes/any(t: t eq 'servicePrincipal') and agent/agentType eq 'AgentIdentity' -
Setting it up properlySOC Identity Responder: contain a compromised account without handing out admin rolesPowerShell
Connect-MgGraph -Scopes "Group.ReadWrite.All","RoleManagement.ReadWrite.Directory" # Role-assignable group for the SOC $group = New-MgGroup -DisplayName "ROLE-SOC-Identity-Responders" -MailEnabled:$false ` -MailNickname "role-soc-identity-responders" -SecurityEnabled -IsAssignableToRole:$true # Make the group eligible for the role for a year New-MgRoleManagementDirectoryRoleEligibilityScheduleRequest -BodyParameter @{ Action = "adminAssign" PrincipalId = $group.Id RoleDefinitionId = "58f930cc-fcf4-4152-852c-1d7dbf502139" # Entra SOC Identity Responder DirectoryScopeId = "/" Justification = "SOC containment role" ScheduleInfo = @{ StartDateTime = Get-Date; Expiration = @{ Type = "AfterDuration"; Duration = "P365D" } } }What each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 4: Creates a group in Microsoft Graph. Makes a change.
- Line 8: Creates a role management directory role eligibility schedule request in Microsoft Graph. Makes a change.
- Line 14: Gets the current date and time.
-
Containment from PowerShellSOC Identity Responder: contain a compromised account without handing out admin rolesPowerShell
Connect-MgGraph -Scopes "User.EnableDisableAccount.All","User.RevokeSessions.All" $upn = "jane.doe@contoso.com" Update-MgUser -UserId $upn -AccountEnabled:$false # 1. stop new sign-ins Revoke-MgUserSignInSession -UserId $upn # 2. invalidate refresh tokensWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 4: Updates a user in Microsoft Graph. Makes a change.
- Line 5: Revokes a user sign in session in Microsoft Graph. Makes a change.
-
3. Review what's already grantedLock down app consent without blocking your usersPowerShell
Connect-MgGraph -Scopes "Directory.Read.All" Get-MgOauth2PermissionGrant -All | Where-Object { $_.Scope -match "Mail\.|Files\.|Sites\.|Directory\." } | ForEach-Object { [pscustomobject]@{ App = (Get-MgServicePrincipal -ServicePrincipalId $_.ClientId).DisplayName ConsentType = $_.ConsentType Scope = $_.Scope } } | Sort-Object App | Format-Table -AutoSizeWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 3: Reads oauth2 permission grant details from Microsoft Graph.
- Line 4: Keeps only the items that match the condition.
- Line 5: Runs the block once for each item coming down the pipeline.
- Line 7: Reads service principal details from Microsoft Graph.
- Line 11: Sorts the results.
-
1. Create a certificateUnattended Graph PowerShell scripts with certificate authenticationPowerShell
$cert = New-SelfSignedCertificate -Subject "CN=Graph-UserReport" ` -CertStoreLocation "Cert:\LocalMachine\My" ` -KeyExportPolicy NonExportable -KeySpec Signature ` -NotAfter (Get-Date).AddYears(1) Export-Certificate -Cert $cert -FilePath C:\Temp\Graph-UserReport.cerWhat each line does
- Line 1: Creates a self signed certificate. Makes a change.
- Line 4: Gets the current date and time.
- Line 6: Saves certificate.
-
3. Connect in the scriptUnattended Graph PowerShell scripts with certificate authenticationPowerShell
Connect-MgGraph -ClientId "<app-id>" -TenantId "<tenant-id>" ` -CertificateThumbprint "<thumbprint>" -NoWelcome Get-MgUser -All -Property DisplayName,UserPrincipalName,AccountEnabled | Export-Csv C:\Reports\users.csv -NoTypeInformationWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 4: Reads user details from Microsoft Graph.
- Line 5: Saves the results as a CSV file you can open in Excel.
-
Graph HTTP
PATCH https://graph.microsoft.com/beta/policies/authenticationmethodspolicy Content-Type: application/json { "optOutSettings": { "passkeyDynamicMigration": true } } -
CLI / shell
az consumption budget create \ --budget-name monthly-dev \ --amount 500 \ --category cost \ --time-grain monthly \ --start-date 2026-09-01 \ --end-date 2027-08-31What each line does
- Line 1: Azure CLI: creates consumption budget. Makes a change.
-
CLI / shell
nslookup stdata.blob.core.windows.net -
PowerShell
# PowerShell equivalent, showing the CNAME chain Resolve-DnsName stdata.blob.core.windows.net | Format-Table Name, Type, IPAddress, NameHostWhat each line does
- Line 2: Looks up DNS records for a name.
-
Switching overKey Vault: move from access policies to Azure RBACCLI / shell
az keyvault update --name kv-app-prod --resource-group rg-app --enable-rbac-authorization trueWhat each line does
- Line 1: Azure CLI: updates key vaults. Makes a change.
-
Finding vaults still on access policiesKey Vault: move from access policies to Azure RBACKQL
// Azure Resource Graph resources | where type == "microsoft.keyvault/vaults" | extend rbac = tobool(properties.enableRbacAuthorization) | where rbac != true | project name, resourceGroup, subscriptionId -
A safer stale-device processSoft delete for Entra device objects: a safety net for device clean-upsPowerShell
Connect-MgGraph -Scopes "Device.Read.All" $cutoff = (Get-Date).AddDays(-90) Get-MgDevice -All -Property DisplayName,OperatingSystem,ApproximateLastSignInDateTime,AccountEnabled | Where-Object { $_.ApproximateLastSignInDateTime -lt $cutoff } | Sort-Object ApproximateLastSignInDateTime | Select-Object DisplayName, OperatingSystem, ApproximateLastSignInDateTime, AccountEnabledWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 3: Gets the current date and time.
- Line 4: Reads device details from Microsoft Graph.
- Line 5: Keeps only the items that match the condition.
- Line 6: Sorts the results.
- Line 7: Keeps only the properties listed, so the output stays small.
-
PowerShell
Connect-MgGraph -Scopes "Device.ReadWrite.All" $cutoff = (Get-Date).AddDays(-90) $stale = Get-MgDevice -All -Property Id,DisplayName,ApproximateLastSignInDateTime,AccountEnabled | Where-Object { $_.AccountEnabled -and $_.ApproximateLastSignInDateTime -lt $cutoff } $stale | Export-Csv stale-devices.csv -NoTypeInformation # keep a record $stale | ForEach-Object { Update-MgDevice -DeviceId $_.Id -AccountEnabled:$false }What each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Gets the current date and time.
- Line 3: Reads device details from Microsoft Graph.
- Line 4: Keeps only the items that match the condition.
- Line 5: Saves the results as a CSV file you can open in Excel.
- Line 6: Runs the block once for each item coming down the pipeline.
-
CLI / shell
IntuneWinAppUtil.exe -c C:\Packages\7zip -s 7z-x64.msi -o C:\Packages\Output -
Install and uninstall commandsPackaging Win32 apps for Intune: detection rules and return codesCLI / shell
msiexec /i "7z-x64.msi" /qn /norestart msiexec /x {23170F69-40C1-2702-0000-000001000000} /qn /norestart -
Example: clear a full temp folderIntune Remediations: find and fix problems before users noticePowerShell
$sizeGB = (Get-ChildItem "$env:SystemRoot\Temp" -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object Length -Sum).Sum / 1GB if ($sizeGB -gt 5) { Write-Output "Temp is $([math]::Round($sizeGB,1)) GB"; exit 1 } Write-Output "Temp OK"; exit 0What each line does
- Line 1: Reads child item details.
- Line 2: Counts the results.
- Line 3: Sends the value down the pipeline (or prints it).
- Line 4: Sends the value down the pipeline (or prints it).
-
Example: clear a full temp folderIntune Remediations: find and fix problems before users noticePowerShell
Get-ChildItem "$env:SystemRoot\Temp" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue Write-Output "Cleaned temp folder"; exit 0What each line does
- Line 1: Reads child item details.
- Line 2: Keeps only the items that match the condition.
- Line 3: Deletes an item. Makes a change.
- Line 4: Sends the value down the pipeline (or prints it).
-
1. Top sign-in failuresSix KQL queries for Entra sign-in logs every admin should keepKQL
SigninLogs | where TimeGenerated > ago(7d) and ResultType != "0" | summarize Count = count() by ResultType, ResultDescription | top 20 by Count -
2. One user's recent sign-insSix KQL queries for Entra sign-in logs every admin should keepKQL
SigninLogs | where TimeGenerated > ago(3d) | where UserPrincipalName =~ "jane.doe@contoso.com" | project TimeGenerated, AppDisplayName, ResultType, ResultDescription, IPAddress, Location = tostring(LocationDetails.countryOrRegion), ConditionalAccessStatus | order by TimeGenerated desc -
3. Sign-ins blocked by Conditional AccessSix KQL queries for Entra sign-in logs every admin should keepKQL
SigninLogs | where TimeGenerated > ago(1d) and ConditionalAccessStatus == "failure" | summarize Count = count() by UserPrincipalName, AppDisplayName | order by Count desc -
4. Successful sign-ins from new countriesSix KQL queries for Entra sign-in logs every admin should keepKQL
let known = SigninLogs | where TimeGenerated between (ago(30d) .. ago(1d)) and ResultType == "0" | distinct UserPrincipalName, Country = tostring(LocationDetails.countryOrRegion); SigninLogs | where TimeGenerated > ago(1d) and ResultType == "0" | extend Country = tostring(LocationDetails.countryOrRegion) | join kind=leftanti known on UserPrincipalName, Country | project TimeGenerated, UserPrincipalName, Country, IPAddress, AppDisplayName -
5. Password spray patternSix KQL queries for Entra sign-in logs every admin should keepKQL
SigninLogs | where TimeGenerated > ago(1h) and ResultType == "50126" | summarize Users = dcount(UserPrincipalName) by IPAddress | where Users > 10 | order by Users desc -
6. Legacy authentication still in useSix KQL queries for Entra sign-in logs every admin should keepKQL
SigninLogs | where TimeGenerated > ago(14d) | where ClientAppUsed !in ("Browser", "Mobile Apps and Desktop clients") | summarize Count = count() by ClientAppUsed, UserPrincipalName, AppDisplayName | order by Count desc -
7. Non-interactive sign-ins by appSix KQL queries for Entra sign-in logs every admin should keepKQL
AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(1d) | summarize Count = count(), Failures = countif(ResultType != "0") by AppDisplayName | order by Count desc -
8. Service principal sign-ins from unexpected IPsSix KQL queries for Entra sign-in logs every admin should keepKQL
AADServicePrincipalSignInLogs | where TimeGenerated > ago(7d) and ResultType == "0" | summarize IPs = make_set(IPAddress, 20), Count = count() by ServicePrincipalName | where array_length(IPs) > 3 | order by Count desc -
The two lock typesResource locks: a cheap insurance policy against the wrong clickCLI / shell
az lock create --name do-not-delete \ --lock-type CanNotDelete \ --resource-group rg-core-networking \ --notes "Hub networking. Raise a change before removing."What each line does
- Line 1: Azure CLI: creates lock. Makes a change.
-
Managing locks at scaleResource locks: a cheap insurance policy against the wrong clickCLI / shell
# Every lock in the current subscription az lock list --output table # Remove one (needs Microsoft.Authorization/locks/delete) az lock delete --name do-not-delete --resource-group rg-core-networkingWhat each line does
- Line 2: Azure CLI: lists lock.
- Line 5: Azure CLI: deletes lock. Makes a change.
-
Where errors show upGroup-based licensing: finding and fixing assignment errorsPowerShell
Connect-MgGraph -Scopes "Group.Read.All" Get-MgGroup -All -Filter "hasMembersWithLicenseErrors eq true" | Select-Object DisplayName, IdWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 3: Reads group details from Microsoft Graph.
- Line 4: Keeps only the properties listed, so the output stays small.
-
Reprocessing after a fixGroup-based licensing: finding and fixing assignment errorsPowerShell
Connect-MgGraph -Scopes "User.ReadWrite.All" $g = Get-MgGroup -Filter "displayName eq 'LIC-M365-E5'" Get-MgGroupMember -GroupId $g.Id -All | ForEach-Object { Invoke-MgLicenseUser -UserId $_.Id }What each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 2: Reads group details from Microsoft Graph.
- Line 3: Reads group member details from Microsoft Graph.
- Line 4: Runs license user in Microsoft Graph.
-
Roll out with the right effectAzure Policy guardrails every subscription should haveCLI / shell
# Assign Allowed locations at a management group, UK regions only az policy assignment create \ --name allowed-locations \ --display-name "Allowed locations: UK" \ --scope "/providers/Microsoft.Management/managementGroups/mg-landingzones" \ --policy "e56962a6-4747-49cd-b67b-bf8b01975c4c" \ --params '{ "listOfAllowedLocations": { "value": ["uksouth","ukwest"] } }'What each line does
- Line 2: Azure CLI: creates policy assignment. Makes a change.
-
How evaluation worksAzure Policy guardrails every subscription should haveCLI / shell
# Run a compliance scan now rather than waiting az policy state trigger-scan --resource-group rg-app-prod # What's non-compliant at a management group? az policy state summarize --management-group mg-landingzones -
3. Update the workflowDeploy from GitHub Actions to Azure without storing a single secretYAML
permissions: id-token: write contents: read jobs: deploy: runs-on: ubuntu-latest environment: production steps: - uses: actions/checkout@v4 - uses: azure/login@v2 with: client-id: ${{ vars.AZURE_CLIENT_ID }} tenant-id: ${{ vars.AZURE_TENANT_ID }} subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - run: az group show --name rg-app -
PowerShell
# Give a Function App's system-assigned identity read access to a storage account $principalId = az functionapp identity assign -g rg-app -n func-app --query principalId -o tsv az role assignment create --assignee $principalId \ --role "Storage Blob Data Reader" \ --scope "/subscriptions/<sub-id>/resourceGroups/rg-data/providers/Microsoft.Storage/storageAccounts/stdata" -
Building a country block safelyNamed locations: getting IP ranges and countries right in Conditional AccessKQL
SigninLogs | where TimeGenerated > ago(30d) and ResultType == "0" | summarize Users = dcount(UserPrincipalName), SignIns = count() by Country = tostring(LocationDetails.countryOrRegion) | order by SignIns desc -
One subscription by CLITurning on Defender CSPM across a landing zoneCLI / shell
az account set --subscription "<subscription-id>" az security pricing create --name CloudPosture --tier Standard az security pricing show --name CloudPostureWhat each line does
- Line 1: Azure CLI: changes your Azure account. Makes a change.
- Line 2: Azure CLI: creates security pricing. Makes a change.
- Line 3: Azure CLI: shows security pricing.
-
Checking coverageTurning on Defender CSPM across a landing zoneKQL
// Azure Resource Graph: Defender CSPM status per subscription securityresources | where type == "microsoft.security/pricings" and name == "CloudPosture" | project subscriptionId, tier = tostring(properties.pricingTier) | order by tier asc -
Reviewing the impactTest Conditional Access safely with report-only mode and What IfKQL
SigninLogs | where TimeGenerated > ago(7d) | mv-expand ConditionalAccessPolicies | where ConditionalAccessPolicies.displayName == "Require compliant device" | where ConditionalAccessPolicies.result == "reportOnlyFailure" | summarize Failures = count() by UserPrincipalName, AppDisplayName | order by Failures desc -
MonitoringBreak-glass accounts done rightKQL
SigninLogs | where UserPrincipalName in~ ("bg-admin1@contoso.onmicrosoft.com", "bg-admin2@contoso.onmicrosoft.com") | project TimeGenerated, UserPrincipalName, IPAddress, AppDisplayName, ResultType -
Connect with the right scopesActivate PIM roles from PowerShell with Microsoft GraphPowerShell
Connect-MgGraph -Scopes "RoleEligibilitySchedule.Read.Directory", "RoleAssignmentSchedule.ReadWrite.Directory" $me = Get-MgUser -UserId (Get-MgContext).AccountWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 4: Reads user details from Microsoft Graph.
-
List your eligible rolesActivate PIM roles from PowerShell with Microsoft GraphPowerShell
$eligible = Get-MgRoleManagementDirectoryRoleEligibilityScheduleInstance -Filter "principalId eq '$($me.Id)'" -ExpandProperty RoleDefinition $eligible | Select-Object @{n="Role";e={$_.RoleDefinition.DisplayName}}, DirectoryScopeId, EndDateTimeWhat each line does
- Line 1: Reads role management directory role eligibility schedule instance details from Microsoft Graph.
- Line 3: Keeps only the properties listed, so the output stays small.
-
PowerShell
$role = $eligible | Where-Object { $_.RoleDefinition.DisplayName -eq "Exchange Administrator" } $params = @{ Action = "selfActivate" PrincipalId = $me.Id RoleDefinitionId = $role.RoleDefinitionId DirectoryScopeId = $role.DirectoryScopeId Justification = "Investigating mail flow issue" ScheduleInfo = @{ StartDateTime = Get-Date Expiration = @{ Type = "AfterDuration"; Duration = "PT2H" } } } New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $paramsWhat each line does
- Line 1: Keeps only the items that match the condition.
- Line 10: Gets the current date and time.
- Line 14: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.
-
Check the result, extend or end earlyActivate PIM roles from PowerShell with Microsoft GraphPowerShell
# Requests you've made, newest first Get-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -Filter "principalId eq '$($me.Id)'" | Sort-Object CreatedDateTime -Descending | Select-Object -First 5 Action, Status, RoleDefinitionId, CreatedDateTime # Finished early? Deactivate rather than leave it running $params.Action = "selfDeactivate" $params.Remove("ScheduleInfo"); $params.Remove("Justification") New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter $paramsWhat each line does
- Line 2: Reads role management directory role assignment schedule request details from Microsoft Graph.
- Line 3: Sorts the results.
- Line 4: Keeps only the properties listed, so the output stays small.
- Line 9: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.
-
Wrap it in a functionActivate PIM roles from PowerShell with Microsoft GraphPowerShell
function Enable-PimRole { param([Parameter(Mandatory)][string]$Role, [string]$Reason = "Planned admin work", [int]$Hours = 1) $me = Get-MgUser -UserId (Get-MgContext).Account $r = Get-MgRoleManagementDirectoryRoleEligibilityScheduleInstance -Filter "principalId eq '$($me.Id)'" -ExpandProperty RoleDefinition | Where-Object { $_.RoleDefinition.DisplayName -eq $Role } if (-not $r) { throw "Not eligible for $Role" } New-MgRoleManagementDirectoryRoleAssignmentScheduleRequest -BodyParameter @{ Action = "selfActivate"; PrincipalId = $me.Id RoleDefinitionId = $r.RoleDefinitionId; DirectoryScopeId = $r.DirectoryScopeId Justification = $Reason ScheduleInfo = @{ StartDateTime = Get-Date; Expiration = @{ Type = "AfterDuration"; Duration = "PT$($Hours)H" } } } } Enable-PimRole -Role "Intune Administrator" -Reason "Deploying compliance policy" -Hours 2What each line does
- Line 1: Turns on a PIM role. Makes a change.
- Line 5: Reads user details from Microsoft Graph.
- Line 6: Reads role management directory role eligibility schedule instance details from Microsoft Graph.
- Line 7: Keeps only the items that match the condition.
- Line 9: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.
- Line 13: Gets the current date and time.
- Line 17: Turns on a PIM role. Makes a change.
-
PowerShell
Connect-MgGraph -Scopes "Application.Read.All" $days = 60 $now = Get-Date Get-MgApplication -All -Property DisplayName,AppId,PasswordCredentials,KeyCredentials | ForEach-Object { $app = $_ $creds = @( $app.PasswordCredentials | ForEach-Object { [pscustomobject]@{ Type="Secret"; Name=$_.DisplayName; End=$_.EndDateTime } } $app.KeyCredentials | ForEach-Object { [pscustomobject]@{ Type="Certificate"; Name=$_.DisplayName; End=$_.EndDateTime } } ) foreach ($c in $creds) { [pscustomobject]@{ App = $app.DisplayName AppId = $app.AppId Type = $c.Type Name = $c.Name Expires = $c.End DaysLeft = [int]($c.End - $now).TotalDays } } } | Where-Object DaysLeft -le $days | Sort-Object DaysLeft | Format-Table -AutoSizeWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 4: Gets the current date and time.
- Line 6: Reads application details from Microsoft Graph.
- Line 7: Runs the block once for each item coming down the pipeline.
- Line 10: Runs the block once for each item coming down the pipeline.
- Line 11: Runs the block once for each item coming down the pipeline.
- Line 24: Keeps only the items that match the condition.
- Line 25: Sorts the results.
- Line 26: Shows the results as a table.
-
Quick inventory with GraphRolling a SAML signing certificate without an outagePowerShell
Connect-MgGraph -Scopes "Application.Read.All" Get-MgServicePrincipal -All -Property DisplayName,KeyCredentials,PreferredSingleSignOnMode | Where-Object PreferredSingleSignOnMode -eq "saml" | ForEach-Object { foreach ($k in $_.KeyCredentials | Where-Object Usage -eq "Verify") { [pscustomobject]@{ App = $_.DisplayName Expires = $k.EndDateTime DaysLeft = [int]($k.EndDateTime - (Get-Date)).TotalDays } } } | Sort-Object DaysLeft | Format-TableWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 3: Reads service principal details from Microsoft Graph.
- Line 4: Keeps only the items that match the condition.
- Line 5: Runs the block once for each item coming down the pipeline.
- Line 6: Keeps only the items that match the condition.
- Line 10: Gets the current date and time.
- Line 13: Sorts the results.
-
Issue one with PowerShellTemporary Access Pass: onboarding users without a passwordPowerShell
Connect-MgGraph -Scopes "UserAuthenticationMethod.ReadWrite.All" $tap = New-MgUserAuthenticationTemporaryAccessPassMethod -UserId "new.starter@contoso.com" -BodyParameter @{ lifetimeInMinutes = 60 isUsableOnce = $true } $tap.TemporaryAccessPassWhat each line does
- Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
- Line 3: Creates a user authentication temporary access pass method in Microsoft Graph. Makes a change.
No scripts match. Try a shorter word.
Read the post before running anything in production. Scripts use example names like contoso.com and need the scopes or roles described in each post.