PowerShell Troubleshooting Toolkit
Purpose: A practical reference for using PowerShell to diagnose, investigate and resolve common Windows and Microsoft 365 problems.
PowerShell can often retrieve information more quickly than navigating through multiple administration portals. It can also expose configuration details and provide administrative capabilities that aren't readily available through the Windows graphical interface.
This guide is intended for support technicians working with Windows devices and Microsoft 365 customer tenants, including environments administered through Microsoft CSP and GDAP.
Important: Before running commands
- -Confirm that you are connected to the correct customer tenant.
- -Check that your account has the required administrative permissions.
- -Prefer read-only diagnostic commands before attempting changes.
- -Be particularly careful with commands that affect multiple users or an entire tenant.
- -Never store customer passwords, access tokens or other credentials in scripts.
- -Record significant administrative changes.
- -Use -WhatIf where supported to preview changes before executing them.
Command classifications
- -Diagnostic: Retrieves information without intentionally changing configuration.
- -Administrative: Changes settings, accounts, permissions or services.
- -System repair: Repairs or modifies the local Windows installation.
Some commands require PowerShell to be run as administrator. Microsoft 365 commands may also require specific delegated permissions, administrative roles and licences.
PowerShell is included with Windows, but Microsoft 365 administration requires additional modules.
Check PowerShell version
$PSVersionTableDisplays the installed PowerShell version and environment information.
List installed modules
Get-Module -ListAvailableShows the PowerShell modules available on the computer.
Find available commands
Get-Command *Mailbox*Searches for commands containing a particular word.
Check command syntax
Get-Command Get-MgUser -SyntaxDisplays the accepted syntax and parameters for a command.
Read command documentation
Get-Help Get-MgUser -FullDisplays detailed help for a command. Some help content may need updating with Update-Help.
Run these commands to install the relevant modules for the current Windows user.
Exchange Online
Install-Module ExchangeOnlineManagement -Scope CurrentUserMicrosoft Graph
Install-Module Microsoft.Graph -Scope CurrentUserMicrosoft Teams
Install-Module MicrosoftTeams -Scope CurrentUserSharePoint Online
Install-Module Microsoft.Online.SharePoint.PowerShell -Scope CurrentUserPnP PowerShell (optional)
Install-Module PnP.PowerShell -Scope CurrentUserPnP PowerShell is a community-maintained module rather than a Microsoft first-party module. Its authentication requirements can differ from Microsoft's official modules.
Exchange Online
Connect-ExchangeOnlineMicrosoft Graph
Connect-MgGraph -Scopes "User.Read.All","Directory.Read.All","Organization.Read.All","AuditLog.Read.All"Microsoft Teams
Connect-MicrosoftTeamsSharePoint Online
Connect-SPOService -Url https://TENANT-admin.sharepoint.comReplace TENANT with the customer's SharePoint tenant name.
Check the current Microsoft Graph connection
Get-MgContextDisplays the current Graph account, tenant and granted scopes.
Disconnect from services
Disconnect-ExchangeOnline -Confirm:$false Disconnect-MgGraph Disconnect-MicrosoftTeamsDisconnecting is particularly important when working with multiple customer tenants.
Important: Connecting to a service does not automatically grant administrative access. Your account must have the necessary roles and delegated permissions. Graph permissions may require administrator consent.
Useful when investigating slow computers, application crashes, Office problems, operating system issues and general device performance.
Display Windows and system information
systeminfoDisplay computer name
hostnameDisplay current Windows user
whoamiDisplay user's UPN
whoami /upnDisplay detailed computer information
Get-ComputerInfoDisplay Windows version
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, OsBuildNumberDisplay operating system details
Get-CimInstance Win32_OperatingSystemDisplay computer and domain information
Get-CimInstance Win32_ComputerSystemCheck disk capacity and available space
Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID, Size, FreeSpaceList running processes
Get-ProcessCheck whether Word is running
Get-Process WINWORDCheck whether Excel is running
Get-Process EXCELCheck whether Outlook is running
Get-Process OUTLOOKFind applications using the most memory
Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10 Name, Id, @{Name="MemoryMB";Expression={[math]::Round($_.WorkingSet64 / 1MB, 2)}}List Windows services
Get-ServiceList stopped services
Get-Service | Where-Object Status -eq 'Stopped'Note that many Windows services are normally stopped until required. A stopped service is not necessarily a fault.
Useful for investigating application crashes, failed services and errors that don't provide a meaningful message to the user.
Display the last 50 application events
Get-WinEvent -LogName Application -MaxEvents 50Display the last 50 system events
Get-WinEvent -LogName System -MaxEvents 50Find application errors from the last 24 hours
Get-WinEvent -FilterHashtable @{ LogName = 'Application' Level = 2 StartTime = (Get-Date).AddDays(-1) } | Select-Object TimeCreated, ProviderName, Id, MessageFind application errors and warnings
Get-WinEvent -FilterHashtable @{ LogName = 'Application' Level = 2,3 StartTime = (Get-Date).AddDays(-1) } | Select-Object TimeCreated, ProviderName, Id, Message- Event levels:
- -2 = Error
- -3 = Warning
System repair – run PowerShell as administrator.
Repair the Windows component store
DISM /Online /Cleanup-Image /RestoreHealthCheck and repair protected Windows system files
sfc /scannowThese commands are useful when Windows itself appears to be malfunctioning. They are not routine fixes for every Office application issue.
Useful when investigating Office activation errors, repeated sign-in prompts, authentication loops, incorrect organisational accounts and conflicts between Windows and Microsoft 365.
Display the current user's UPN
whoami /upnDisplay Windows device registration
dsregcmd /statusOne of the most useful commands when investigating Microsoft 365 authentication problems.
- Important fields include:
3.1 Check Windows identity and Entra registration Field Meaning AzureAdJoined Whether the device is joined to Microsoft Entra ID DomainJoined Whether the device is joined to an on-premises AD domain WorkplaceJoined Whether the device has a registered work account TenantId The associated Entra tenant ID DeviceId The registered device ID AzureAdPrt Whether a Primary Refresh Token is present A device can have different combinations of these states depending on how it is configured.
Check whether the Windows authentication broker package is installed
Get-AppxPackage Microsoft.AAD.BrokerPluginThe AAD Broker Plugin is associated with Windows authentication and Web Account Manager (WAM).
Check the TokenBroker service
Get-Service TokenBrokerDisplays the service status.
Check the current date and time
Get-DateCheck Windows time synchronisation
w32tm /query /statusRequest time synchronisation
w32tm /resyncThis changes local system time synchronisation. Administrator permissions may be required.
Check 64-bit Office installation entries
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -Match "Microsoft 365|Office" | Select-Object DisplayName, DisplayVersionCheck 32-bit Office installation entries
Get-ItemProperty HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -Match "Microsoft 365|Office" | Select-Object DisplayName, DisplayVersionThese commands can help identify multiple Office installations or older versions.
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration"Displays Click-to-Run installation information, where applicable.
Microsoft provides an official activation reset procedure for Microsoft 365 Apps.
- It can help resolve:
- -Persistent activation errors.
- -Incorrect cached account information.
- -Corrupt licensing tokens.
- -Repeated authentication prompts.
- -Problems following account or tenant changes.
Use Microsoft's official procedure rather than manually deleting licensing files, authentication tokens or registry keys.
Important: Do not casually remove Windows work accounts, clear all Credential Manager entries or use dsregcmd /leave. These actions can affect Windows SSO, OneDrive, Teams, device management and Entra registration.
Reference: Reset Microsoft 365 Apps activation state
Useful when investigating email delivery, domain configuration, Outlook connectivity, Microsoft 365 authentication and problems accessing online services.
Check general DNS resolution
Resolve-DnsName example.comCheck MX records
Resolve-DnsName example.com -Type MXCheck TXT records
Resolve-DnsName example.com -Type TXTUseful for inspecting SPF and domain verification records.
Check Autodiscover
Resolve-DnsName autodiscover.example.comCheck a CNAME record
Resolve-DnsName example.com -Type CNAMEAlternative DNS lookup
nslookup example.comCheck HTTPS connectivity to Outlook
Test-NetConnection outlook.office365.com -Port 443Check SMTP submission connectivity
Test-NetConnection smtp.office365.com -Port 587Check Microsoft sign-in connectivity
Test-NetConnection login.microsoftonline.com -Port 443Check Teams connectivity
Test-NetConnection teams.microsoft.com -Port 443A successful test confirms that a TCP connection can be established. It does not confirm that authentication, licensing or the application itself is working.
Display complete IP configuration
ipconfig /allDisplay configured DNS servers
Get-DnsClientServerAddressDisplay network configuration
Get-NetIPConfigurationClear local DNS cache
ipconfig /flushdnsThis changes the local DNS resolver cache.
Display WinHTTP proxy settings
netsh winhttp show proxyUseful when Office applications cannot connect even though a web browser appears to work.
Note that WinHTTP proxy settings and browser proxy settings are not necessarily identical.
These commands use Microsoft Graph PowerShell.
They are useful for managing customer users, licences, groups, sign-in records and administrative roles.
Retrieve a specific user
Get-MgUser -UserId user@domain.dkList all users
Get-MgUser -AllDisplay important user properties
Get-MgUser -UserId user@domain.dk -Property DisplayName,UserPrincipalName,AccountEnabled,UserType,CreatedDateTime | Format-ListCheck user sign-in activity
Get-MgUser -UserId user@domain.dk -Property SignInActivitySign-in activity availability depends on the tenant's licensing, permissions and reporting access.
List subscribed licence SKUs
Get-MgSubscribedSkuCheck licences assigned to a user
Get-MgUserLicenseDetail -UserId user@domain.dkDisplay licence names and IDs
Get-MgUserLicenseDetail -UserId user@domain.dk | Select-Object SkuPartNumber, SkuIdDisplay available licence quantities
Get-MgSubscribedSku | Select-Object SkuPartNumber, ConsumedUnits, @{Name="Available";Expression={$_.PrepaidUnits.Enabled - $_.ConsumedUnits}}This is particularly useful when a customer has licence assignment problems or limited available licences.
Retrieve recent sign-in records
Get-MgAuditLogSignIn -Filter "userPrincipalName eq 'user@domain.dk'" -Top 20Retrieve failed sign-in records
Get-MgAuditLogSignIn -Filter "userPrincipalName eq 'user@domain.dk' and status/errorCode ne 0" -Top 20- Useful when investigating:
- -Incorrect passwords.
- -MFA failures.
- -Conditional Access blocks.
- -Device compliance problems.
- -Authentication errors.
The account requires appropriate audit-log permissions. Log retention and availability depend on the tenant's licensing and configuration.
List deleted directory objects
Get-MgDirectoryDeletedItem -AllList deleted users
Get-MgDirectoryDeletedItemAsUser -AllRestore a deleted user
Restore-MgDirectoryDeletedItem -DirectoryObjectId <USER-ID>Administrative action. Only works while the deleted object remains recoverable.
List groups
Get-MgGroup -AllList members of a group
Get-MgGroupMember -GroupId <GROUP-ID> -AllCheck a user's group and directory memberships
Get-MgUserMemberOf -UserId user@domain.dkList activated directory roles
Get-MgDirectoryRoleList members of a role
Get-MgDirectoryRoleMember -DirectoryRoleId <ROLE-ID>
Exchange Online PowerShell is particularly useful for diagnosing mailbox problems, permissions, forwarding, mail flow and email delivery.
Connect first
Connect-ExchangeOnlineRetrieve mailbox information
Get-EXOMailbox -Identity user@domain.dkDisplay important mailbox properties
Get-EXOMailbox -Identity user@domain.dk | Format-List DisplayName, PrimarySmtpAddress, RecipientTypeDetails, ProhibitSendQuotaCheck mailbox size
Get-EXOMailboxStatistics -Identity user@domain.dkDisplay mailbox folders
Get-EXOMailboxFolderStatistics -Identity user@domain.dkCheck Full Access and other mailbox permissions
Get-MailboxPermission -Identity user@domain.dkCheck Send As permissions
Get-RecipientPermission -Identity user@domain.dkCheck calendar permissions
Get-MailboxFolderPermission -Identity user@domain.dk:\CalendarCheck mailbox-level forwarding
Get-Mailbox user@domain.dk | Format-List ForwardingAddress, ForwardingSmtpAddress, DeliverToMailboxAndForwardList inbox rules
Get-InboxRule -Mailbox user@domain.dkInclude hidden inbox rules
Get-InboxRule -Mailbox user@domain.dk -IncludeHiddenParticularly useful when investigating compromised accounts or suspicious email forwarding.
List shared mailboxes
Get-EXOMailbox -RecipientTypeDetails SharedMailboxCheck a specific shared mailbox
Get-EXOMailbox -Identity shared@domain.dk | Format-List DisplayName, PrimarySmtpAddress, RecipientTypeDetailsList transport rules
Get-TransportRuleList accepted domains
Get-AcceptedDomainList anti-spam policies
Get-HostedContentFilterPolicyList anti-spam policy rules
Get-HostedContentFilterRuleOne of the most useful tools for investigating missing or delayed emails.
Search for messages sent to a recipient
Get-MessageTraceV2 -RecipientAddress user@domain.dkSearch for messages sent by a user
Get-MessageTraceV2 -SenderAddress user@domain.dkSearch the previous two days
Get-MessageTraceV2 -RecipientAddress user@domain.dk ` -StartDate (Get-Date).AddDays(-2) ` -EndDate (Get-Date)Retrieve detailed delivery information
Get-MessageTraceDetailV2 -MessageTraceId <TRACE-ID> -RecipientAddress user@domain.dkMessage trace V2 supports searches over the previous 90 days. Each query can cover a maximum of 10 days, and result limits apply.
Get-CASMailbox user@domain.dk | Format-List MAPIEnabled, OWAEnabled, ActiveSyncEnabled, PopEnabled, ImapEnabled, SmtpClientAuthenticationDisabledUseful for investigating Outlook, mobile access, POP, IMAP and SMTP AUTH issues.
Connect first
Connect-MicrosoftTeamsRetrieve Teams user information
Get-CsOnlineUser -Identity user@domain.dkDisplay selected properties
Get-CsOnlineUser -Identity user@domain.dk | Format-List DisplayName, UserPrincipalName, AccountEnabled, TeamsUpgradeEffectiveModeCheck user policy assignments
Get-CsUserPolicyAssignment -Identity user@domain.dkList meeting policies
Get-CsTeamsMeetingPolicyList messaging policies
Get-CsTeamsMessagingPolicyList calling policies
Get-CsTeamsCallingPolicyGet-CsTenantRetrieves tenant-level Teams configuration. Useful when investigating missing features, meeting restrictions, calling problems and unexpected policy behaviour.
SharePoint Online PowerShell can retrieve site information, storage usage and sharing configuration.
Connect first
Connect-SPOService -Url https://TENANT-admin.sharepoint.comReplace TENANT with the customer's SharePoint tenant name.
List SharePoint sites
Get-SPOSite -Limit AllRetrieve a specific site
Get-SPOSite -Identity https://tenant.sharepoint.com/sites/sitenameDisplay storage and sharing information
Get-SPOSite -Identity https://tenant.sharepoint.com/sites/sitename | Format-List Url, Owner, StorageUsageCurrent, StorageQuota, SharingCapabilityRetrieve tenant-wide SharePoint settings
Get-SPOTenant | Format-List SharingCapability, DefaultSharingLinkType, OneDriveStorageQuotaA user's OneDrive is technically a SharePoint personal site.
Find the user's OneDrive site
Get-SPOSite -IncludePersonalSite $true -Limit All | Where-Object Owner -eq "user@domain.dk"Check OneDrive storage usage
Get-SPOSite -Identity <ONEDRIVE-URL> | Format-List Url, Owner, StorageUsageCurrent, StorageQuotaUseful when a customer asks how much OneDrive storage is being used.
PnP PowerShell provides additional capabilities for inspecting SharePoint sites, libraries, permissions and files.
It is community-maintained and has its own authentication requirements. Use its official documentation and check the current authentication setup before using it in production.
Reference: PnP PowerShell documentation
Useful for retrieving information about a customer tenant, verified domains, subscriptions and administrative changes.
These commands use Microsoft Graph.
Retrieve organisation information
Get-MgOrganizationList tenant domains
Get-MgDomain -AllCheck a specific domain
Get-MgDomain -DomainId example.comDisplay important domain properties
Get-MgDomain -DomainId example.com | Format-List Id, IsVerified, IsDefault, AuthenticationTypeList subscribed licence SKUs
Get-MgSubscribedSkuDisplay licence availability
Get-MgSubscribedSku | Select-Object SkuPartNumber, ConsumedUnits, @{Name="Available";Expression={$_.PrepaidUnits.Enabled - $_.ConsumedUnits}}Useful when investigating licence assignment problems or checking whether a customer has available licences.
Note that this retrieves tenant subscription information, not the complete commercial CSP catalogue or all billing details.
Retrieve recent directory audit events
Get-MgAuditLogDirectoryAudit -Top 20Display important audit event details
Get-MgAuditLogDirectoryAudit -Top 50 | Select-Object ActivityDateTime, ActivityDisplayName, Result, InitiatedByUseful when investigating changes made to users, groups, roles and other directory objects.
Security investigations may require Microsoft Graph, Exchange Online PowerShell or dedicated Defender tools.
The commands below are useful for identifying suspicious activity and reviewing security-related changes.
List risky users
Get-MgRiskyUser -AllRetrieve risk detections
Get-MgRiskDetection -Top 20These commands require suitable Entra ID Protection permissions and licensing.
Get-MgAuditLogDirectoryAudit -Top 50 | Select-Object ActivityDateTime, ActivityDisplayName, Result, InitiatedByUseful for identifying unexpected administrative changes.
Check hidden inbox rules
Get-InboxRule -Mailbox user@domain.dk -IncludeHiddenCheck mailbox forwarding
Get-Mailbox user@domain.dk | Format-List ForwardingAddress, ForwardingSmtpAddressCheck transport rules
Get-TransportRuleThese commands can help identify suspicious forwarding configurations, especially when investigating a potentially compromised mailbox.
Important: Finding a suspicious configuration does not by itself establish that an account has been compromised. Investigate sign-in activity, permissions and other evidence before making changes.
The commands in this section can change customer configurations. Always verify the customer, account and intended result before running them.
Reset a user's password
Update-MgUser -UserId user@domain.dk -PasswordProfile @{ Password = "TemporaryPassword" ForceChangePasswordNextSignIn = $true }Administrative action. Use an approved secure method to handle temporary passwords. Never save them in scripts or logs.
Block user sign-in
Update-MgUser -UserId user@domain.dk -AccountEnabled:$falseEnable user sign-in
Update-MgUser -UserId user@domain.dk -AccountEnabled:$trueRevoke sign-in sessions
Revoke-MgUserSignInSession -UserId user@domain.dkThis invalidates refresh tokens and requires the user to authenticate again as applicable.
Assign a licence
Set-MgUserLicense -UserId user@domain.dk ` -AddLicenses @{SkuId="<SKU-ID>"} ` -RemoveLicenses @()Remove a licence
Set-MgUserLicense -UserId user@domain.dk ` -AddLicenses @() ` -RemoveLicenses @("<SKU-ID>")Replace the SKU ID with the actual licence SKU ID retrieved from the tenant.
Check the effects of removing a licence before proceeding, particularly for Exchange mailboxes and OneDrive data.
Enable mailbox forwarding
Set-Mailbox user@domain.dk -ForwardingSmtpAddress external@example.comDisable mailbox forwarding
Set-Mailbox user@domain.dk -ForwardingSmtpAddress $null -ForwardingAddress $nullEnable SMTP AUTH for a mailbox
Set-CASMailbox user@domain.dk -SmtpClientAuthenticationDisabled $falseDisable SMTP AUTH for a mailbox
Set-CASMailbox user@domain.dk -SmtpClientAuthenticationDisabled $trueSMTP AUTH may also be disabled at organisation level. A mailbox-level setting does not override every organisation-wide restriction.
Add Full Access
Add-MailboxPermission -Identity shared@domain.dk ` -User user@domain.dk ` -AccessRights FullAccess ` -InheritanceType AllAdd Send As permission
Add-RecipientPermission -Identity shared@domain.dk ` -Trustee user@domain.dk ` -AccessRights SendAsRemove Full Access
Remove-MailboxPermission -Identity shared@domain.dk ` -User user@domain.dk ` -AccessRights FullAccess ` -InheritanceType AllFull Access and Send As are separate permissions. Full Access does not automatically grant Send As.
These techniques help make PowerShell faster and more useful in everyday support work.
Find disabled users
Get-MgUser -All | Where-Object AccountEnabled -eq $falseFind processes using significant CPU time
Get-Process | Where-Object CPU -gt 100Get-EXOMailbox user@domain.dk | Format-List DisplayName, PrimarySmtpAddress, RecipientTypeDetailsUse Select-Object or Format-List to display only the information relevant to the problem.
Sort processes by CPU time
Get-Process | Sort-Object CPU -DescendingExport tenant users
Get-MgUser -All | Select-Object DisplayName, UserPrincipalName, AccountEnabled | Export-Csv "C:\Temp\Users.csv" -NoTypeInformation -Encoding UTF8Useful when preparing reports or reviewing larger sets of data.
Get-ComputerInfo | Out-File "C:\Temp\ComputerInfo.txt"Find mailbox commands
Get-Command *Mailbox*Find licence-related commands
Get-Command *License*Find user-related commands
Get-Command *User*Get-Command Set-Mailbox -SyntaxAlways check the accepted parameters before using an unfamiliar command.
Get-Help Set-Mailbox -Full
Everyday Support – Quick Reference
These are the commands I would recommend learning first.
| Problem | Command |
|---|---|
| Check Windows/Entra connection | dsregcmd /status |
| Check user's identity | whoami /upn |
| Check Windows time | w32tm /query /status |
| Check DNS | Resolve-DnsName domain.dk |
| Test Outlook connectivity | Test-NetConnection outlook.office365.com -Port 443 |
| Check installed Office versions | Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |
| Check Windows errors | Get-WinEvent -LogName Application -MaxEvents 50 |
| Check mailbox exists | Get-EXOMailbox user@domain.dk |
| Check mailbox size | Get-EXOMailboxStatistics user@domain.dk |
| Check mailbox permissions | Get-MailboxPermission user@domain.dk |
| Check hidden inbox rules | Get-InboxRule -Mailbox user@domain.dk -IncludeHidden |
| Trace an email | Get-MessageTraceV2 -RecipientAddress user@domain.dk |
| Check user's licence | Get-MgUserLicenseDetail -UserId user@domain.dk |
| Check tenant licences | Get-MgSubscribedSku |
| Check sign-in failures | Get-MgAuditLogSignIn -Filter "userPrincipalName eq 'user@domain.dk' and status/errorCode ne 0" |
| Check domain verification | Get-MgDomain -DomainId domain.dk |
Recommended Official Documentation
The following Microsoft documentation should be used as the primary reference when checking command syntax, module requirements and supported procedures.
Exchange Online
Microsoft Teams
SharePoint
Office activation
Internal Support Guidelines
When adding or using commands in MS365 Sherpa, each command should ideally have the following information:
- Command: The exact PowerShell command.
- Purpose: What the command does.
- When to use it: The customer complaint or problem it helps investigate.
- Requirements: Module, connection, permissions and administrator privileges.
- Risk: Whether the command is diagnostic or changes the environment.
- Expected result: What the technician should look for.
The objective is to make PowerShell a practical support tool, not simply a collection of commands.
Golden rule: Diagnose first, change second.
