The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Inspect AD platform levels | Get-ADForest |
Select-Object ForestMode; Get-ADDomain |
Select-Object DomainMode | View examples |
| Check the AD module | Get-Module -ListAvailable ActiveDirectory |
Select-Object Name, Version, Path | View examples |
| List KDS root keys | Get-KdsRootKey |
Select-Object KeyId, EffectiveTime, CreationTime | View examples |
| Create a production KDS key | Add-KdsRootKey -EffectiveImmediately | View examples |
| Check KDS operational events | Get-WinEvent -FilterHashtable `
@{LogName='Microsoft-Windows-KdsSvc/Operational'; `
Id=4004} -MaxEvents 5 | View examples |
| Preview a host group | New-ADGroup -Name 'GG-gmsaFinance-Hosts' -GroupScope `
DomainLocal -GroupCategory Security -WhatIf | View examples |
| Preview host authorization | Add-ADGroupMember -Identity 'GG-gmsaFinance-Hosts' `
-Members 'APP01$' -WhatIf | View examples |
| Preview a gMSA | New-ADServiceAccount -Name 'gmsaFinance' -DNSHostName `
'finance.corp.example.com' -WhatIf | View examples |
| Preview an sMSA | New-ADServiceAccount -Name 'msaLegacy' `
-RestrictToSingleComputer -WhatIf | View examples |
| Preview a dMSA | New-ADServiceAccount -Name 'dmsaFinance' -DNSHostName `
'dmsaFinance.corp.example.com' `
-CreateDelegatedServiceAccount -WhatIf | View examples |
| Inspect a managed account | Get-ADServiceAccount -Identity 'gmsaFinance' -Properties `
PrincipalsAllowedToRetrieveManagedPassword,ServicePrincipalNames | View examples |
| Preview retrieval policy | Set-ADServiceAccount -Identity 'gmsaFinance' `
-PrincipalsAllowedToRetrieveManagedPassword `
'GG-gmsaFinance-Hosts' -WhatIf | View examples |
| Preview local installation | Install-ADServiceAccount -Identity 'gmsaFinance' -WhatIf | View examples |
| Test local readiness | Test-ADServiceAccount -Identity 'gmsaFinance' | View examples |
| Check SPN ownership | setspn.exe -Q 'HTTP/finance.corp.example.com' | View examples |
| Register a unique SPN | setspn.exe -S 'HTTP/finance.corp.example.com' `
'CORP\gmsaFinance$' | View examples |
| Assign a Windows service | sc.exe config FinanceWorker obj= 'CORP\gmsaFinance$' `
password= '' | View examples |
| Build a task principal | New-ScheduledTaskPrincipal -UserId 'CORP\gmsaFinance$' `
-LogonType Password -RunLevel Limited | View examples |
| Inspect service identity | Get-CimInstance Win32_Service -Filter "Name='FinanceWorker'" |
Select-Object Name, StartName, State; sc.exe qmanagedaccount FinanceWorker | View examples |
| Read Kerberos events | Get-WinEvent -LogName `
'Microsoft-Windows-Security-Kerberos/Operational' `
-MaxEvents 100 | View examples |
| Preview local uninstall | Uninstall-ADServiceAccount -Identity 'gmsaFinance' `
-WhatIf | View examples |
| Preview directory removal | Remove-ADServiceAccount -Identity 'gmsaFinance' -Server `
'dc01.corp.example.com' -WhatIf | View examples |
Managed Service Accounts replace administrator-known service passwords with keys managed through Active Directory Domain Services. Choose a standalone MSA (sMSA) for one compatible host, a group MSA (gMSA) for a farm or reusable domain identity, and evaluate delegated MSA (dMSA) only in a qualified Windows Server 2025 design. Establish supported forest, domain, schema, domain-controller, host, Kerberos, DNS, time, and application conditions first. Then authorize only the computer identities that must retrieve the managed password, bind SPNs to exactly one principal, deploy through a staged change, and verify both authentication and the workload's effective access.
Step by step
Detailed examples
Choose the account type from workload and platform constraints
An sMSA, introduced with Windows Server 2008 R2, is bound to one domain-joined Windows computer and cannot provide one identity across a farm. A gMSA, introduced with Windows Server 2012, lets multiple authorized Windows Server hosts retrieve the same automatically managed account secret. Microsoft's current guidance says both forest and domain functional levels should be Windows Server 2012 or later for full gMSA support; also confirm an updated schema, reachable writable DCs, supported host OS, DNS, synchronized time, Kerberos encryption compatibility, and 64-bit administrative tooling. A dMSA is a distinct Windows Server 2025 feature, not a new name for gMSA. Use the ActiveDirectory module from RSAT or an administrative server, and delegate only the exact directory permissions needed instead of making every operator a Domain Admin. Application support matters: an executable that decrypts or persists its own password may not support any MSA even when Windows can install one. Feature installation or host policy might require elevation and a reboot; ordinary AD object creation does not, but replication always matters.
$server = 'dc01.corp.example.com'
$PSVersionTable | Select-Object PSEdition, PSVersion
Get-Module -ListAvailable ActiveDirectory | Select-Object Name, Version, Path
Get-ADForest -Server $server | Select-Object Name, ForestMode, SchemaMaster, Domains
Get-ADDomain -Server $server | Select-Object DNSRoot, DomainMode, PDCEmulator
Get-ADDomainController -Identity $server |
Select-Object HostName, OperatingSystem, Site, IsReadOnly, OperationMasterRoles Note: Treat the reported modes as eligibility inputs, not proof that the schema, replication, KDS, host, and application requirements are all satisfied.
Create one KDS root deliberately and allow convergence
KDS root keys are forest configuration data used by domain controllers to derive gMSA and dMSA credentials. Inventory existing keys before creating anything: multiple roots are not a rotation strategy and can complicate diagnosis. Add-KdsRootKey requires Domain Admins, Enterprise Admins, or equivalent delegated authority and must target an appropriate writable Windows Server 2012-or-later DC. In production, -EffectiveImmediately creates the key on the selected DC, but Microsoft documents a wait of up to ten hours so replication can converge before gMSAs are used. The backdated -EffectiveTime ((Get-Date).AddHours(-10)) shortcut is only for an isolated single-DC test environment; using it in production defeats the safety interval. Verify replication health and KdsSvc event 4004 rather than treating elapsed wall time alone as success. Creating a root normally needs no server reboot. Deleting and recreating a root is hazardous because cached old keys can remain in use and may require restarting KDC services across DCs; follow a Microsoft-supported recovery plan instead.
Import-Module Kds
Get-KdsRootKey |
Select-Object KeyId, EffectiveTime, CreationTime, DomainController
Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-KdsSvc/Operational'
Id = 4004
} -MaxEvents 10 | Select-Object TimeCreated, Id, LevelDisplayName, Message
# Run once only under an approved forest change, then allow up to ten hours.
# Add-KdsRootKey -EffectiveImmediately Note: Add-KdsRootKey does not provide a safe simulation of forest-wide effects. Never uncomment it without approval, and never create another root merely because an existing deployment is not yet effective.
Treat password retrieval as permission to become the account
PrincipalsAllowedToRetrieveManagedPassword controls which computer accounts or groups may obtain a gMSA's managed password. A compromised authorized host can act as the gMSA, so use a dedicated security group per account, admit only the workload's computer identities, protect membership changes, and monitor the ACL. Do not use broad groups such as Domain Computers. Separate this host-eligibility group from resource authorization groups granted to the gMSA itself. Set-ADServiceAccount replaces the supplied retrieval-principal set; read the current value and compute an intentional desired set instead of accidentally dropping active hosts. Membership and attribute changes replicate asynchronously. A newly authorized computer can retain an old machine token; after replication, a controlled reboot is the most deterministic refresh, though some environments use an approved computer-ticket purge. Do not restart a production server until workload redundancy and rollback have been verified.
$server = 'dc01.corp.example.com'
$hostGroup = Get-ADGroup -Identity 'GG-gmsaFinance-Hosts' -Server $server
$hostAccount = Get-ADComputer -Identity 'APP01' -Server $server
$hostGroup, $hostAccount |
Select-Object Name, ObjectClass, ObjectGUID, SID, DistinguishedName
Add-ADGroupMember -Identity $hostGroup.ObjectGUID `
-Members $hostAccount.ObjectGUID -Server $server -WhatIf
Set-ADServiceAccount -Identity 'gmsaFinance' `
-PrincipalsAllowedToRetrieveManagedPassword $hostGroup.ObjectGUID `
-Server $server -WhatIf Note: WhatIf previews supported directory mutations only. It does not evaluate effective ACLs, replication, group-token refresh, host compromise risk, or whether every current consumer is represented.
Create the identity with explicit names, encryption, hosts, and SPNs
A gMSA name must be unique across the forest. DNSHostName identifies the account in DNS form but does not create an A, AAAA, or load-balancer record; provision and govern service DNS separately. Register only SPNs that clients actually use, including aliases or listener names, and confirm each SPN is unique before creation. Prefer AES-capable hosts and set KerberosEncryptionType according to the domain's tested policy; removing RC4 without checking every participant can break authentication. ManagedPasswordIntervalInDays defaults to 30 and can be set only when the gMSA is created, so choose it through risk and compatibility testing rather than attempting an in-place change later. sMSA uses -RestrictToSingleComputer and must be associated with its single computer. Keep descriptions, owners, environment, and change records in governed inventory because the AD object alone cannot reveal every service, task, application pool, container, ACL, or secret-store dependency.
$server = 'dc01.corp.example.com'
$hosts = Get-ADGroup -Identity 'GG-gmsaFinance-Hosts' -Server $server
$params = @{
Name = 'gmsaFinance'
DNSHostName = 'finance.corp.example.com'
Description = 'Finance API identity; owner Finance Platform; CHG-2042'
PrincipalsAllowedToRetrieveManagedPassword = $hosts.ObjectGUID
ServicePrincipalNames = @('HTTP/finance.corp.example.com')
KerberosEncryptionType = @('AES128','AES256')
ManagedPasswordIntervalInDays = 30
Server = $server
}
$existing = Get-ADServiceAccount -Identity $params.Name -Server $server `
-Properties DNSHostName,ServicePrincipalNames,KerberosEncryptionType,`
ManagedPasswordIntervalInDays,PrincipalsAllowedToRetrieveManagedPassword `
-ErrorAction SilentlyContinue
if ($existing) {
$existing | Select-Object Name,SamAccountName,ObjectGUID,DNSHostName,Enabled,`
ServicePrincipalNames,KerberosEncryptionType,ManagedPasswordIntervalInDays,`
PrincipalsAllowedToRetrieveManagedPassword
} else {
New-ADServiceAccount @params -WhatIf
} $server = 'dc01.corp.example.com'
$existing = Get-ADServiceAccount -Identity 'msaLegacy' -Server $server `
-ErrorAction SilentlyContinue
if ($existing) {
Add-ADComputerServiceAccount -Identity 'APP01' `
-ServiceAccount $existing -Server $server -WhatIf
} else {
New-ADServiceAccount -Name 'msaLegacy' -RestrictToSingleComputer `
-Description 'Single-host legacy agent on APP01' -Server $server -WhatIf
} Note: WhatIf does not create an object for a later command in the same script. Execute and verify the approved creation before previewing association. Do not deploy an sMSA to a farm.
Install and test from each authorized host
Run Install-ADServiceAccount locally in an elevated Windows PowerShell session after the account, KDS key, retrieval ACL, security-group membership, and replication are ready. The cmdlet changes the local computer and verifies host eligibility; it does not configure an application to use the account. Test-ADServiceAccount returning True means the local host can authenticate with the current managed credentials, not that an SPN is correct or that the service can reach databases, files, certificates, network endpoints, or other resources. Run both steps on every permitted host and record the account SID and computer identity. If testing fails, first validate DC discovery, DNS, time, secure channel, supported encryption types, replicated retrieval authorization, and KDS readiness. After adding the computer to its host group, plan a controlled reboot if the machine's group token has not refreshed. Installing a gMSA itself normally does not require reboot, but changing a service or application identity requires a service, task, or app-pool restart.
$account = 'gmsaFinance'
$env:COMPUTERNAME
Test-ComputerSecureChannel -Verbose
Resolve-DnsName 'dc01.corp.example.com'
Install-ADServiceAccount -Identity $account -WhatIf
# After the approved installation is executed:
Test-ADServiceAccount -Identity $account
Get-ADServiceAccount -Identity $account |
Select-Object Name, SamAccountName, SID, Enabled Note: Test on the actual workload host. A successful result on an administrator workstation proves only that workstation's eligibility.
Bind supported workloads without ever handling the managed password
Use the account as DOMAIN\name$ and leave the password empty only in interfaces that explicitly support managed service accounts. Service Control Manager, IIS application pools, and Task Scheduler support managed service identities, but third-party installers and wrappers may reject them or store credentials incorrectly. Preserve the current identity, dependencies, recovery settings, task definition, or IIS configuration before change; grant only required logon rights and resource ACLs; stage one redundant instance; then restart and test. For Windows services, verify sc.exe qmanagedaccount reports TRUE after binding; a false IsManagedAccount flag can let a cached secret work initially and then break after rollover. For scheduled tasks, a PowerShell principal using Password logon type is the established noninteractive pattern even though no administrator supplies a password; validate it on the exact supported OS and task engine. IIS uses SpecificUser with the gMSA name and an empty password through IIS Manager, AppCmd, or the WebAdministration provider. An SPN represents the client-facing service name, not necessarily the physical host. Query first and use setspn -S rather than -A so duplicate detection remains active. Never enable unconstrained delegation by default; use no delegation or a narrowly reviewed constrained/resource-based design only when a documented double-hop requires it.
$serviceName = 'FinanceWorker'
$before = Get-CimInstance Win32_Service -Filter "Name='$serviceName'"
$before | Select-Object Name, StartName, StartMode, State, PathName
Test-ADServiceAccount -Identity 'gmsaFinance'
# Approved maintenance window: preserve rollback data before changing identity.
sc.exe config $serviceName obj= 'CORP\gmsaFinance$' password= ''
Get-CimInstance Win32_Service -Filter "Name='$serviceName'" |
Select-Object Name, StartName, State
sc.exe qmanagedaccount $serviceName Note: sc.exe has no WhatIf and changes the Service Control Manager database immediately. Stop or drain the instance as the vendor requires, then restart and run an application-level authentication test.
$principal = New-ScheduledTaskPrincipal `
-UserId 'CORP\gmsaFinance$' -LogonType Password -RunLevel Limited
$action = New-ScheduledTaskAction `
-Execute 'C:\Program Files\Finance\Reconcile.exe'
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable
$task = New-ScheduledTask -Action $action -Principal $principal -Settings $settings
$task | Select-Object -ExpandProperty Principal
# Register-ScheduledTask -TaskName 'Finance-Reconcile' -InputObject $task Note: Registration is intentionally omitted from the example because it mutates Task Scheduler. Add bounded triggers, execution limits, working-directory behavior, and task-history monitoring before deployment.
Import-Module WebAdministration
Get-ItemProperty 'IIS:\AppPools\FinanceApi' -Name processModel |
Select-Object identityType, userName, loadUserProfile
# During an approved drain, set SpecificUser to CORP\gmsaFinance$ with no password
# through IIS Manager or a tested AppCmd/WebAdministration deployment, then recycle
# only this pool and verify Windows authentication plus every downstream dependency. Note: Do not place a password placeholder in source control. Export a protected IIS configuration backup and confirm the application vendor supports gMSA before changing the pool.
Keep dMSA and container workflows explicitly version-scoped
dMSA was introduced in Windows Server 2025 and Microsoft currently limits setup to Windows Server 2025 devices. A schema extension or functional-level change alone is not sufficient: a Windows Server 2025 DC must be available, the KDS root must be ready, every participating host and the management tools must support the feature, and creation or migration requires Domain Admins, Enterprise Admins, or equivalent delegated permissions. Enable the DelegatedMSAEnabled Kerberos policy on each client device before using a standalone dMSA or superseding a legacy account. Microsoft's current standalone procedure also authorizes the exact machine and sets msDS-DelegatedMSAState to 3; treat that documented state change as a reviewed directory mutation and verify it afterward. Migration instead uses Start-, Complete-, Undo-, and Reset-ADServiceAccountMigration. Complete disables the superseded account path, so update every machine that uses the old account, retain the original object, and keep a tested undo window rather than deleting it. Validate Security-Kerberos Operational events 307, 308, and 309. Windows containers use gMSA credential-spec metadata, not a domain join inside the container. Domain-joined hosts can retrieve through authorized computer accounts; Windows Server 2019 and later can also use a separately engineered ccg.exe plug-in and portable identity for non-domain-joined hosts. Orchestrators must protect credential specs and retrieval identities, constrain scheduling to eligible nodes, and provide DC network reachability.
$server = 'dc2025.corp.example.com'
$machine = Get-ADComputer -Identity 'APP01' -Server $server
$dmsa = Get-ADServiceAccount -Identity 'dmsaFinance' -Server $server `
-Properties 'msDS-DelegatedMSAState',PrincipalsAllowedToRetrieveManagedPassword `
-ErrorAction SilentlyContinue
if (-not $dmsa) {
New-ADServiceAccount -Name 'dmsaFinance' `
-DNSHostName 'dmsaFinance.corp.example.com' `
-CreateDelegatedServiceAccount -KerberosEncryptionType AES256 `
-Server $server -WhatIf
} else {
Set-ADServiceAccount -Identity $dmsa `
-PrincipalsAllowedToRetrieveManagedPassword $machine.ObjectGUID `
-Server $server -WhatIf
Set-ADServiceAccount -Identity $dmsa `
-Replace @{'msDS-DelegatedMSAState' = 3} -Server $server -WhatIf
$dmsa | Select-Object Name,ObjectGUID,Enabled,`
'msDS-DelegatedMSAState',PrincipalsAllowedToRetrieveManagedPassword
} Note: WhatIf does not create the dMSA for subsequent steps. Execute and verify each approved mutation before previewing the next; deploy DelegatedMSAEnabled=1 through governed client policy and validate the final state before binding a workload.
Get-CredentialSpec | Select-Object Name, Path
Get-Content 'C:\ProgramData\docker\CredentialSpecs\finance.json' -Raw |
ConvertFrom-Json | Select-Object -ExpandProperty ActiveDirectoryConfig Note: A credential spec contains account metadata rather than the managed password, but it is still security-sensitive configuration. Verify its source, ACL, orchestrator distribution, eligible nodes, and gMSA SPNs.
Diagnose the identity chain in order and preserve audit evidence
Troubleshoot from directory and host prerequisites toward the workload: confirm the exact account SID and properties, KDS readiness, retrieval principals, group membership on the write DC and another DC, computer secure channel, DNS and time, local installation, Test-ADServiceAccount, service logon identity, unique SPNs, Kerberos tickets, then resource authorization. A generic access-denied response can come from password retrieval, logon rights, SPN duplication, encryption mismatch, delegation, stale tickets, or the target resource's ACL. Enable and collect only the relevant KdsSvc and Security-Kerberos Operational channels under the organization's logging policy; dMSA events 307-309 are particularly useful for migration, permission-add, and key-fetch activity. Audit changes to managed-account objects and host groups through directory-service change auditing and privileged-access logs. Never export msDS-ManagedPassword or grant users read access to it for troubleshooting, because possession of the secret permits impersonation until password rollover.
$server = 'dc01.corp.example.com'
$account = Get-ADServiceAccount -Identity 'gmsaFinance' -Server $server `
-Properties DNSHostName,ServicePrincipalNames,KerberosEncryptionType,`
PrincipalsAllowedToRetrieveManagedPassword,PasswordLastSet
$account | Select-Object Name,SamAccountName,SID,DNSHostName,Enabled,PasswordLastSet,`
KerberosEncryptionType,ServicePrincipalNames,PrincipalsAllowedToRetrieveManagedPassword
Test-ComputerSecureChannel -Verbose
Test-ADServiceAccount -Identity $account
setspn.exe -Q 'HTTP/finance.corp.example.com'
Get-CimInstance Win32_Service -Filter "Name='FinanceWorker'" |
Select-Object Name, StartName, State, ExitCode
Get-WinEvent -LogName 'Microsoft-Windows-Security-Kerberos/Operational' `
-MaxEvents 100 | Select-Object TimeCreated, Id, LevelDisplayName, Message Note: Do not query or serialize msDS-ManagedPassword. Redact domain topology, SIDs, hostnames, and event data before attaching diagnostics outside approved administrative systems.
Let AD rotate credentials and retire consumers before the object
AD and authorized hosts manage routine gMSA password rollover; administrators should not know, copy, schedule, or distribute the password. The managed interval defaults to 30 days and is immutable after creation. If policy requires a different interval, design a replacement account and migrate consumers rather than attempting to edit the existing interval. Before retirement, inventory services, tasks, IIS pools, containers, SPNs, local logon rights, ACLs, database roles, certificates, delegation settings, host retrieval groups, monitoring, and disaster-recovery jobs. Move each workload to a replacement identity, restart it, obtain fresh Kerberos tickets, and verify application behavior. Then remove host authorization and local installations. Uninstall-ADServiceAccount affects the local cache or sMSA installation; Remove-ADServiceAccount deletes the directory object but does not reconfigure consumers. Preserve rollback through the observation window, remove SPNs and grants only when ownership is proven, and delete the AD object last through a reviewed change. No reboot is inherently required for removal, but running workloads and stale tickets can preserve old state until restarted or renewed.
$server = 'dc01.corp.example.com'
$account = Get-ADServiceAccount -Identity 'gmsaFinance' -Server $server `
-Properties ServicePrincipalNames,PrincipalsAllowedToRetrieveManagedPassword,`
ManagedPasswordIntervalInDays,PasswordLastSet
$account | Select-Object Name,ObjectGUID,SID,Enabled,PasswordLastSet,`
ManagedPasswordIntervalInDays,ServicePrincipalNames,`
PrincipalsAllowedToRetrieveManagedPassword
Get-CimInstance Win32_Service |
Where-Object StartName -eq 'CORP\gmsaFinance$' |
Select-Object Name, StartName, State, PathName
Get-ScheduledTask | Where-Object {$_.Principal.UserId -eq 'CORP\gmsaFinance$'} |
Select-Object TaskPath, TaskName, State
Uninstall-ADServiceAccount -Identity $account -WhatIf
Remove-ADServiceAccount -Identity $account.ObjectGUID -Server $server -WhatIf Note: Run local consumer discovery on every eligible host. WhatIf does not find application-specific references, revoke resource permissions, delete SPNs safely, or prove that rollback is no longer needed.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
- Microsoft LearnService Accounts in Windows Serverlearn.microsoft.com
- Microsoft LearnGroup Managed Service Accounts Overviewlearn.microsoft.com
- Microsoft LearnManage Group Managed Service Accountslearn.microsoft.com
- Microsoft LearnCreate a Key Distribution Service (KDS) Root Keylearn.microsoft.com
- Microsoft LearnNew-ADServiceAccountlearn.microsoft.com
- Microsoft LearnSet-ADServiceAccountlearn.microsoft.com
- Microsoft LearnInstall-ADServiceAccountlearn.microsoft.com
- Microsoft LearnTest-ADServiceAccountlearn.microsoft.com
- Microsoft LearnSet Up Delegated Managed Service Accountslearn.microsoft.com
- Microsoft LearnCreate gMSAs for Windows Containerslearn.microsoft.com
- Microsoft LearnError 1069 when starting a service with a gMSAlearn.microsoft.com
- Microsoft LearnUninstall-ADServiceAccountlearn.microsoft.com
- Microsoft LearnRemove-ADServiceAccountlearn.microsoft.com
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



