· Uwe Janke
Commands / Sync-sqmLoginsToAlwaysOn
Always On

Sync-sqmLoginsToAlwaysOn

Keeps logins in sync across all replicas of an Availability Group. A login that exists on any replica is created, with SID and password hash, on every replica that lacks it, regardless of which one is primary. A password changed on one replica is applied to the others. Logins dropped on a replica and other conflicts are reported, never overwritten.

Module: sqmSQLTool
Requires: dbatools
ShouldProcess: Yes (Medium)
Output: PSCustomObject[]

Why not just primary to secondary?

Logins are not part of the Availability Group, and the primary role says nothing about where a login was created last. A login created on node A in the afternoon, followed by a failover to node B before the nightly sync, exists only on the new secondary. A primary→secondary sync running on B never sees it, and the application cannot log in on the new primary. Since v1.9.191.0 the default -SyncMode Union reads all replicas and fills the gaps in every direction. The previous behaviour is still available as -SyncMode Primary.

Execution Flow (SyncMode Union)

START 1. Resolve AG, primary and all replicas -SyncMode Union? Primary Copy-sqmLogins primary to each secondary 2. Read every replica: logins + snapshot master.dbo.sqmLoginSyncState, created on first run unreachable: Failed, next run foreach login that is missing on a replica dropped there before? (tombstone) yes report, not recreated event 9004 first run and target = primary? yes baseline tombstone, report (9004) sources differ in SID or password? yes conflict, not copied event 9004 ShouldProcess? no WhatIf row Copy-sqmLogins holder -> target create only (no DROP), SID + password hash, orphan repair 3. Existing logins: passwords and differences password changed since last run: newest wins (ALTER LOGIN HASHED) 4. Update the snapshot on every replica gone on all replicas: tombstone removed Return one row per action DONE
Tombstones. Each replica keeps its last seen login set in master.dbo.sqmLoginSyncState. A login that was on a replica before and is missing now was dropped there on purpose, so it is not recreated from another replica. Drop it on the other replicas too, or distribute it again with -ResetTombstone. First run: secondaries receive missing logins as before; logins missing on the primary are only reported, because the tool cannot know whether they were deleted there deliberately in the past. Check the report after the first run.
Password changes (v1.9.192.0+). If a SQL login has the same SID on all replicas but a different password hash, the password that was set last is applied to the other replicas with ALTER LOGIN ... WITH PASSWORD = <hash> HASHED, never DROP. A change is detected by PasswordLastSetTime rising on a replica since the last run (stored in the snapshot, in UTC), not by comparing hashes: SQL Server 2025 stores passwords in a new format (0x0300) and rewrites an older 0x0200 hash at the next login without touching PasswordLastSetTime, so the same password has different hashes on 2022 and 2025. A 0x0300 hash is never written to a replica older than SQL Server 2025; that case is reported. CHECK_POLICY and CHECK_EXPIRATION are switched off for the change (HASHED requires it) and restored afterwards. Two competing changes less than 60 seconds apart are only reported. A rollback script with the old hashes is written to -BackupPath first. Default database, language, disabled state and different SIDs are only reported.
Scope. Never copied: sa (SID 0x01, also when renamed), ##MS_* certificate logins and local machine accounts (HOST\user of any replica). Unless -IncludeSystemLogins is set: sysadmin members, NT SERVICE\*, NT AUTHORITY\* and BUILTIN\*.

Parameters

ParameterTypeRequiredDescription
-SqlInstanceStringOptionalAn instance of the AG, normally the primary. Default: $env:COMPUTERNAME.
-AvailabilityGroupNameStringOptionalAG to sync. If omitted, the first AG on the instance is used (with a warning if there are several).
-SyncModeStringOptionalUnion (default): missing logins in every direction, tombstones and conflicts only reported. Primary: previous behaviour, primary to secondaries, -Force overwrites existing logins.
-HashChangeStringOptionalUnion only. Newest (default): a password changed on one replica is applied to the others. Report: only report the difference.
-ResetTombstoneString[]OptionalUnion only. Exact login names whose tombstone is removed on all replicas before the sync, so they are distributed again.
-SqlCredentialPSCredentialOptionalCredential for all replicas. Union mode uses one credential for all replicas (this one, otherwise -SourceCredential).
-SourceCredentialPSCredentialOptionalPrimary mode: credential for the primary.
-DestinationCredentialPSCredentialOptionalPrimary mode: credential for the secondaries.
-LoginString[]OptionalOnly these logins (wildcards allowed).
-ExcludeLoginString[]OptionalLogins to skip (wildcards allowed).
-IncludeSystemLoginsSwitchOptionalAlso include sysadmin members and NT SERVICE\*, NT AUTHORITY\*, BUILTIN\*. sa and ##MS_* are never copied.
-SkipSecondaryServersString[]OptionalSecondary replicas to leave out (maintenance).
-AdjustAuthModeSwitchOptionalAdjust the authentication mode of a target replica to match the source if needed.
-RestartServiceIfRequiredSwitchOptionalRestart the SQL Server service on a target replica if its authentication mode was changed.
-DisablePolicySwitchOptionalDisable the configured policy on the target during the copy (default: $true).
-AdModuleActionStringOptionalInstall, Skip or Abort if the ActiveDirectory module is missing. Not set: Install interactively, Skip in a SQL Agent job.
-AuditAdOrphansSwitchOptionalAfter the sync, report Windows logins whose AD account no longer exists (event 9003). Detection only.
-ForceSwitchOptionalPrimary mode only, ignored in Union mode. Overwrites existing logins on the secondaries (DROP + CREATE). Default $true in Primary mode.
-ForceIncludeOnlyString[]OptionalPrimary mode with -Force: only update these logins.
-ForceExcludeString[]OptionalPrimary mode with -Force: additional logins to leave untouched.
-SafeForceModeBoolOptionalPrimary mode with -Force: exclude sysadmins, the Agent account and system logins (default $true).
-BackupLoginsSwitchOptionalPrimary mode with -Force: script the existing logins of each secondary to a .sql file first.
-BackupPathStringOptionalFolder for login backups and password rollback scripts. Default: configured output path.
-BackupRetentionDaysIntOptionalDelete login backups (and audit reports) older than this many days. Default 7, 0 keeps all.
-NoReportSwitchOptionalDo not write backup files (job context).
-EnableExceptionSwitchOptionalThrow instead of returning a Failed row.
-WhatIf / -ConfirmSwitchOptionalStandard ShouldProcess support. With -WhatIf nothing is copied and no snapshot is written.

Return Value

Union: one PSCustomObject per action with AvailabilityGroup, SyncMode, Action (Copy, PasswordSync, Tombstone, Conflict, ReadReplica, ResetTombstone, UpdateState), LoginName, SourceReplica, TargetReplica, Status (Success, Warning, Failed, Skipped, WhatIf), Message, Timestamp. Rows with status Warning need a decision and are also written to the Application log (source sqmSQLTool, event 9004); Failed rows raise event 9002.

Primary: one object per secondary with PrimaryReplica, SecondaryReplica, Status, LoginsCount, OrphansRepaired, BackupFile, Error.

Examples

Example 1, Sync all replicas of an AG

Sync-sqmLoginsToAlwaysOn -SqlInstance "SQL01" -AvailabilityGroupName "AG_PROD"

Example 2, Preview: what would be copied and reported

Sync-sqmLoginsToAlwaysOn -SqlInstance "SQL01" -AvailabilityGroupName "AG_PROD" -WhatIf |
    Where-Object Status -ne 'Success' | Format-Table Action, LoginName, TargetReplica, Status, Message

Example 3, Distribute a reported login again

Sync-sqmLoginsToAlwaysOn -SqlInstance "SQL01" -AvailabilityGroupName "AG_PROD" -ResetTombstone "svc_app"

Example 4, Report password differences instead of applying them

Sync-sqmLoginsToAlwaysOn -SqlInstance "SQL01" -AvailabilityGroupName "AG_PROD" -HashChange Report

Example 5, Only application logins, with AD orphan audit

Sync-sqmLoginsToAlwaysOn -SqlInstance "SQL01" -Login "DOMAIN\App*","svc_app" -AuditAdOrphans

Example 6, Previous behaviour: primary to secondaries, new logins only

Sync-sqmLoginsToAlwaysOn -SqlInstance "SQL01" -SyncMode Primary -Force:$false
For unattended runs use the standard job: Install-sqmStandardJob -Name AgLoginSync on every replica. It runs daily and right after a failover (Agent alert on message 1480).