azureblog.co.uk
← 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
  1. powershell2 lineshover a line number for notes
    Connect-MgGraph -Scopes ServiceHealth.Read.All
    Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/issues/EX1550543"
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Calls the Microsoft Graph API directly.
  2. powershell5 lineshover a line number for notes
    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 -NoTypeInformation
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Reads device management managed device details from Microsoft Graph.
    3. Line 3: Keeps only the items that match the condition.
    4. Line 4: Keeps only the properties listed, so the output stays small.
    5. Line 5: Saves the results as a CSV file you can open in Excel.
  3. powershell1 linehover a line number for notes
    Resolve-DnsName -Type TXT _dmarc.contoso.com | Select-Object -ExpandProperty Strings
    What each line does
    1. Line 1: Looks up DNS records for a name.
  4. shell1 line
    nslookup -type=TXT _dmarc.contoso.com
  5. powershell6 lines
    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
  6. kql3 lines
    az graph query -q "resources
    | where type =~ 'microsoft.compute/cloudservices'
    | project name, resourceGroup, subscriptionId, location" -o table
  7. powershell6 lineshover a line number for notes
    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
    1. Line 1: Signs in to Azure.
    2. Line 4: Reads role assignment details from Azure.
    3. Line 5: Keeps only the properties listed, so the output stays small.
  8. shell2 lineshover a line number for notes
    az role assignment list --all --role Owner --include-inherited \
        --query "[].{who:principalName, type:principalType, scope:scope}" -o table
    What each line does
    1. Line 1: Azure CLI: lists role assignments.
  9. powershell6 lineshover a line number for notes
    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, PrincipalDisplayName
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Reads service principal details from Microsoft Graph.
    3. Line 3: Runs the block once for each item coming down the pipeline.
    4. Line 4: Reads service principal app role assigned to details from Microsoft Graph.
    5. Line 5: Keeps only the properties listed, so the output stays small.
    6. Line 6: Sorts the results.
  10. PowerShell
    powershell6 lines1 changes something · hover a line number for notes
    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
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 3: Reads directory deleted item as user details from Microsoft Graph.
    3. Line 4: Keeps only the properties listed, so the output stays small.
    4. Line 6: Restores a directory deleted item in Microsoft Graph. Makes a change.
  11. PowerShell
    powershell6 lines1 changes something · hover a line number for notes
    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
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Gets the current date and time.
    3. Line 3: Creates an item. Makes a change.
    4. Line 4: Reads identity conditional access policy details from Microsoft Graph.
    5. Line 5: Turns the results into JSON text.
  12. kql8 lines
    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
  13. powershell9 lineshover a line number for notes
    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
    1. Line 1: Reads web app details from Azure.
    2. Line 2: Reads web app details from Azure.
    3. Line 9: Keeps only the items that match the condition.
  14. powershell5 lineshover a line number for notes
    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 -NoTypeInformation
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Reads device management managed device details from Microsoft Graph.
    3. Line 3: Keeps only the items that match the condition.
    4. Line 4: Keeps only the properties listed, so the output stays small.
    5. Line 5: Saves the results as a CSV file you can open in Excel.
  15. kql6 lines
    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
  16. shell3 lines1 changes something · hover a line number for notes
    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
    1. Line 3: Azure CLI: changes webapp config. Makes a change.
  17. powershell21 lines1 changes something · hover a line number for notes
    $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 -AutoSize
    What each line does
    1. Line 1: Reads subscription details from Azure.
    2. Line 2: Changes a context in Azure. Makes a change.
    3. Line 3: Reads resource details from Azure.
    4. Line 4: Keeps only the items that match the condition.
    5. Line 5: Runs the block once for each item coming down the pipeline.
    6. Line 6: Reads web app details from Azure.
    7. Line 7: Keeps only the items that match the condition.
    8. Line 21: Sorts the results.
  18. shell9 lines1 changes something · hover a line number for notes
    # 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 production
    What each line does
    1. Line 2: Azure CLI: changes functionapp config appsettings. Makes a change.
  19. CLI / shell
    shell6 lines1 changes something · hover a line number for notes
    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 Manager
    What each line does
    1. Line 1: Azure CLI: changes your Azure account. Makes a change.
  20. After onboarding: switch things onAzure Arc for servers: the complete setup guide
    PowerShell
    powershell8 lineshover a line number for notes
    $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_token
    What each line does
    1. Line 4: Runs web request.
    2. Line 6: Reads content details.
    3. Line 7: Runs web request.
    4. Line 8: Reads JSON text into objects you can work with.
  21. kql3 lines
    Resources
    | where type == 'microsoft.hybridcompute/machines'
    | summarize Servers = count() by Status = tostring(properties.status)
  22. kql16 lines
    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
  23. powershell2 lineshover a line number for notes
    Connect-MgGraph -Scopes Policy.Read.All
    (Get-MgPolicyAuthorizationPolicy).DefaultUserRolePermissions | Format-List
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Reads authorization policy details from Microsoft Graph.
  24. powershell2 lines1 changes something · hover a line number for notes
    Connect-MgGraph -Scopes Policy.ReadWrite.Authorization
    Update-MgPolicyAuthorizationPolicy -DefaultUserRolePermissions @{ AllowedToCreateApps = $false }
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Updates an authorization policy in Microsoft Graph. Makes a change.
  25. powershell7 lineshover a line number for notes
    $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-List
    What each line does
    1. Line 1: Reads item property details.
    2. Line 6: Reads secure boot uefi details.
    3. Line 7: Shows every property of each result as a list.
  26. kql5 lines
    DeviceInfo
    | where Timestamp > ago(7d)
    | where OSPlatform startswith "WindowsServer2012"
    | summarize arg_max(Timestamp, OSPlatform, OSBuild, PublicIP) by DeviceName
    | order by DeviceName asc
  27. kql5 lines
    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
  28. http1 line
    GET https://graph.microsoft.com/beta/auditLogs/signIns?$filter=signInEventTypes/any(t: t eq 'servicePrincipal') and agent/agentType eq 'AgentIdentity'
  29. powershell15 lines2 change something · hover a line number for notes
    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
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 4: Creates a group in Microsoft Graph. Makes a change.
    3. Line 8: Creates a role management directory role eligibility schedule request in Microsoft Graph. Makes a change.
    4. Line 14: Gets the current date and time.
  30. powershell5 lines2 change something · hover a line number for notes
    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 tokens
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 4: Updates a user in Microsoft Graph. Makes a change.
    3. Line 5: Revokes a user sign in session in Microsoft Graph. Makes a change.
  31. PowerShell
    powershell11 lineshover a line number for notes
    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 -AutoSize
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 3: Reads oauth2 permission grant details from Microsoft Graph.
    3. Line 4: Keeps only the items that match the condition.
    4. Line 5: Runs the block once for each item coming down the pipeline.
    5. Line 7: Reads service principal details from Microsoft Graph.
    6. Line 11: Sorts the results.
  32. powershell6 lines1 changes something · hover a line number for notes
    $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.cer
    What each line does
    1. Line 1: Creates a self signed certificate. Makes a change.
    2. Line 4: Gets the current date and time.
    3. Line 6: Saves certificate.
  33. powershell5 lineshover a line number for notes
    Connect-MgGraph -ClientId "<app-id>" -TenantId "<tenant-id>" `
      -CertificateThumbprint "<thumbprint>" -NoWelcome
    
    Get-MgUser -All -Property DisplayName,UserPrincipalName,AccountEnabled |
      Export-Csv C:\Reports\users.csv -NoTypeInformation
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 4: Reads user details from Microsoft Graph.
    3. Line 5: Saves the results as a CSV file you can open in Excel.
  34. http8 lines
    PATCH https://graph.microsoft.com/beta/policies/authenticationmethodspolicy
    Content-Type: application/json
    
    {
      "optOutSettings": {
        "passkeyDynamicMigration": true
      }
    }
  35. shell7 lines1 changes something · hover a line number for notes
    az consumption budget create \
      --budget-name monthly-dev \
      --amount 500 \
      --category cost \
      --time-grain monthly \
      --start-date 2026-09-01 \
      --end-date 2027-08-31
    What each line does
    1. Line 1: Azure CLI: creates consumption budget. Makes a change.
  36. shell1 line
    nslookup stdata.blob.core.windows.net
  37. powershell2 lineshover a line number for notes
    # PowerShell equivalent, showing the CNAME chain
    Resolve-DnsName stdata.blob.core.windows.net | Format-Table Name, Type, IPAddress, NameHost
    What each line does
    1. Line 2: Looks up DNS records for a name.
  38. shell1 line1 changes something · hover a line number for notes
    az keyvault update --name kv-app-prod --resource-group rg-app --enable-rbac-authorization true
    What each line does
    1. Line 1: Azure CLI: updates key vaults. Makes a change.
  39. Finding vaults still on access policiesKey Vault: move from access policies to Azure RBAC
    KQL
    kql6 lines
    // Azure Resource Graph
    resources
    | where type == "microsoft.keyvault/vaults"
    | extend rbac = tobool(properties.enableRbacAuthorization)
    | where rbac != true
    | project name, resourceGroup, subscriptionId
  40. powershell7 lineshover a line number for notes
    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, AccountEnabled
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 3: Gets the current date and time.
    3. Line 4: Reads device details from Microsoft Graph.
    4. Line 5: Keeps only the items that match the condition.
    5. Line 6: Sorts the results.
    6. Line 7: Keeps only the properties listed, so the output stays small.
  41. powershell6 lineshover a line number for notes
    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
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Gets the current date and time.
    3. Line 3: Reads device details from Microsoft Graph.
    4. Line 4: Keeps only the items that match the condition.
    5. Line 5: Saves the results as a CSV file you can open in Excel.
    6. Line 6: Runs the block once for each item coming down the pipeline.
  42. shell1 line
    IntuneWinAppUtil.exe -c C:\Packages\7zip -s 7z-x64.msi -o C:\Packages\Output
  43. shell2 lines
    msiexec /i "7z-x64.msi" /qn /norestart
    msiexec /x {23170F69-40C1-2702-0000-000001000000} /qn /norestart
  44. PowerShell
    powershell4 lineshover a line number for notes
    $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 0
    What each line does
    1. Line 1: Reads child item details.
    2. Line 2: Counts the results.
    3. Line 3: Sends the value down the pipeline (or prints it).
    4. Line 4: Sends the value down the pipeline (or prints it).
  45. PowerShell
    powershell4 lines1 changes something · hover a line number for notes
    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 0
    What each line does
    1. Line 1: Reads child item details.
    2. Line 2: Keeps only the items that match the condition.
    3. Line 3: Deletes an item. Makes a change.
    4. Line 4: Sends the value down the pipeline (or prints it).
  46. kql4 lines
    SigninLogs
    | where TimeGenerated > ago(7d) and ResultType != "0"
    | summarize Count = count() by ResultType, ResultDescription
    | top 20 by Count
  47. kql7 lines
    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
  48. KQL
    kql4 lines
    SigninLogs
    | where TimeGenerated > ago(1d) and ConditionalAccessStatus == "failure"
    | summarize Count = count() by UserPrincipalName, AppDisplayName
    | order by Count desc
  49. KQL
    kql8 lines
    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
  50. kql5 lines
    SigninLogs
    | where TimeGenerated > ago(1h) and ResultType == "50126"
    | summarize Users = dcount(UserPrincipalName) by IPAddress
    | where Users > 10
    | order by Users desc
  51. kql5 lines
    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
  52. kql4 lines
    AADNonInteractiveUserSignInLogs
    | where TimeGenerated > ago(1d)
    | summarize Count = count(), Failures = countif(ResultType != "0") by AppDisplayName
    | order by Count desc
  53. 8. Service principal sign-ins from unexpected IPsSix KQL queries for Entra sign-in logs every admin should keep
    KQL
    kql5 lines
    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
  54. shell4 lines1 changes something · hover a line number for notes
    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
    1. Line 1: Azure CLI: creates lock. Makes a change.
  55. shell5 lines1 changes something · hover a line number for notes
    # 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-networking
    What each line does
    1. Line 2: Azure CLI: lists lock.
    2. Line 5: Azure CLI: deletes lock. Makes a change.
  56. powershell4 lineshover a line number for notes
    Connect-MgGraph -Scopes "Group.Read.All"
    
    Get-MgGroup -All -Filter "hasMembersWithLicenseErrors eq true" |
      Select-Object DisplayName, Id
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 3: Reads group details from Microsoft Graph.
    3. Line 4: Keeps only the properties listed, so the output stays small.
  57. powershell5 lineshover a line number for notes
    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
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 2: Reads group details from Microsoft Graph.
    3. Line 3: Reads group member details from Microsoft Graph.
    4. Line 4: Runs license user in Microsoft Graph.
  58. CLI / shell
    shell7 lines1 changes something · hover a line number for notes
    # 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
    1. Line 2: Azure CLI: creates policy assignment. Makes a change.
  59. shell5 lines
    # 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
  60. yaml16 lines
    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
  61. powershell5 lines
    # 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"
  62. kql4 lines
    SigninLogs
    | where TimeGenerated > ago(30d) and ResultType == "0"
    | summarize Users = dcount(UserPrincipalName), SignIns = count() by Country = tostring(LocationDetails.countryOrRegion)
    | order by SignIns desc
  63. CLI / shell
    shell3 lines2 change something · hover a line number for notes
    az account set --subscription "<subscription-id>"
    az security pricing create --name CloudPosture --tier Standard
    az security pricing show --name CloudPosture
    What each line does
    1. Line 1: Azure CLI: changes your Azure account. Makes a change.
    2. Line 2: Azure CLI: creates security pricing. Makes a change.
    3. Line 3: Azure CLI: shows security pricing.
  64. kql5 lines
    // 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
  65. kql7 lines
    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
  66. kql3 lines
    SigninLogs
    | where UserPrincipalName in~ ("bg-admin1@contoso.onmicrosoft.com", "bg-admin2@contoso.onmicrosoft.com")
    | project TimeGenerated, UserPrincipalName, IPAddress, AppDisplayName, ResultType
  67. PowerShell
    powershell4 lineshover a line number for notes
    Connect-MgGraph -Scopes "RoleEligibilitySchedule.Read.Directory",
                            "RoleAssignmentSchedule.ReadWrite.Directory"
    
    $me = Get-MgUser -UserId (Get-MgContext).Account
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 4: Reads user details from Microsoft Graph.
  68. powershell3 lineshover a line number for notes
    $eligible = Get-MgRoleManagementDirectoryRoleEligibilityScheduleInstance -Filter "principalId eq '$($me.Id)'" -ExpandProperty RoleDefinition
    
    $eligible | Select-Object @{n="Role";e={$_.RoleDefinition.DisplayName}}, DirectoryScopeId, EndDateTime
    What each line does
    1. Line 1: Reads role management directory role eligibility schedule instance details from Microsoft Graph.
    2. Line 3: Keeps only the properties listed, so the output stays small.
  69. powershell14 lines1 changes something · hover a line number for notes
    $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 $params
    What each line does
    1. Line 1: Keeps only the items that match the condition.
    2. Line 10: Gets the current date and time.
    3. Line 14: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.
  70. Check the result, extend or end earlyActivate PIM roles from PowerShell with Microsoft Graph
    PowerShell
    powershell9 lines1 changes something · hover a line number for notes
    # 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 $params
    What each line does
    1. Line 2: Reads role management directory role assignment schedule request details from Microsoft Graph.
    2. Line 3: Sorts the results.
    3. Line 4: Keeps only the properties listed, so the output stays small.
    4. Line 9: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.
  71. powershell17 lines3 change something · hover a line number for notes
    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 2
    What each line does
    1. Line 1: Turns on a PIM role. Makes a change.
    2. Line 5: Reads user details from Microsoft Graph.
    3. Line 6: Reads role management directory role eligibility schedule instance details from Microsoft Graph.
    4. Line 7: Keeps only the items that match the condition.
    5. Line 9: Creates a role management directory role assignment schedule request in Microsoft Graph. Makes a change.
    6. Line 13: Gets the current date and time.
    7. Line 17: Turns on a PIM role. Makes a change.
  72. powershell26 lineshover a line number for notes
    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 -AutoSize
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 4: Gets the current date and time.
    3. Line 6: Reads application details from Microsoft Graph.
    4. Line 7: Runs the block once for each item coming down the pipeline.
    5. Line 10: Runs the block once for each item coming down the pipeline.
    6. Line 11: Runs the block once for each item coming down the pipeline.
    7. Line 24: Keeps only the items that match the condition.
    8. Line 25: Sorts the results.
    9. Line 26: Shows the results as a table.
  73. PowerShell
    powershell13 lineshover a line number for notes
    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-Table
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 3: Reads service principal details from Microsoft Graph.
    3. Line 4: Keeps only the items that match the condition.
    4. Line 5: Runs the block once for each item coming down the pipeline.
    5. Line 6: Keeps only the items that match the condition.
    6. Line 10: Gets the current date and time.
    7. Line 13: Sorts the results.
  74. powershell7 lines1 changes something · hover a line number for notes
    Connect-MgGraph -Scopes "UserAuthenticationMethod.ReadWrite.All"
    
    $tap = New-MgUserAuthenticationTemporaryAccessPassMethod -UserId "new.starter@contoso.com" -BodyParameter @{
        lifetimeInMinutes = 60
        isUsableOnce      = $true
    }
    $tap.TemporaryAccessPass
    What each line does
    1. Line 1: Signs in to Microsoft Graph with the permissions (scopes) listed.
    2. Line 3: Creates a user authentication temporary access pass method in Microsoft Graph. Makes a change.
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.