PowerShell script to rotate Windows local administrator passwords
Local administrator accounts provide a break-glass route into Windows systems that domain authentication cannot reach. Their shared, long-lived credentials are still common on servers, appliances and virtual machines, so rotating them regularly reduces the value of a copied password without changing how the account is administered.
A useful PowerShell workflow generates a random password on the endpoint, applies it with the native local-account cmdlets and returns only a status record. The script below never accepts, displays or stores the secret, which prevents it from appearing in transcripts, process arguments or plaintext configuration files.
The approach suits Australian organisations in Sydney, Melbourne and Brisbane that combine on-premises Windows servers with Microsoft 365 or Azure. Local administrator accounts remain common on standalone infrastructure and appliances, even where engineers prefer centrally managed identities for everyday work.
Rotation must still include secure recovery. An unknown password is useful only when a privileged access workflow or Microsoft LAPS can reset the account, and organisations should avoid disabling their final administrative path while attempting to improve credential hygiene.
Prepare and Confirm the Target Account
Confirm the exact target before changing anything. Get-LocalUser lists local SAM accounts, while domain administrators come from Active Directory. A renamed built-in administrator can be identified by its local SID ending in -500; run Get-LocalUser | Where-Object { $_.SID.Value -like '*-500' } rather than assuming the name remains Administrator.
Keep the scope to named accounts. Members of the local Administrators group can include service identities and delegated operators whose credentials have different owners. For VMware-hosted systems, align the workflow with the site's VMware virtualisation guidance, particularly for golden images and cloned templates.
Generate a Strong Local Password
Password quality matters as much as length. The script uses RandomNumberGenerator, rejects modulo bias and guarantees uppercase, lowercase, numeric and symbol characters, producing a value that should satisfy typical Windows complexity rules.
#requires -Version 5.1
#requires -RunAsAdministrator
[CmdletBinding(SupportsShouldProcess)]
param(
[string]$AccountName = 'Administrator',
[ValidateRange(16, 64)]
[int]$PasswordLength = 32
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$user = Get-LocalUser -Name $AccountName -ErrorAction Stop
$sets = @(
'ABCDEFGHJKLMNPQRSTUVWXYZ',
'abcdefghijkmnopqrstuvwxyz',
'23456789',
'!@#$%_-+='
)
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
function Get-CryptoIndex {
param(
[int]$Maximum,
[System.Security.Cryptography.RandomNumberGenerator]$Random
)
$limit = [int]([math]::Floor(256 / $Maximum) * $Maximum)
do {
$sample = New-Object byte[] 1
$Random.GetBytes($sample)
} until ($sample[0] -lt $limit)
return ($sample[0] % $Maximum)
}
$characters = [System.Collections.Generic.List[char]]::new()
foreach ($set in $sets) {
$index = Get-CryptoIndex -Maximum $set.Length -Random $rng
[void]$characters.Add($set[$index])
}
$pool = $sets -join ''
while ($characters.Count -lt $PasswordLength) {
$index = Get-CryptoIndex -Maximum $pool.Length -Random $rng
[void]$characters.Add($pool[$index])
}
for ($i = $characters.Count - 1; $i -gt 0; $i--) {
$j = Get-CryptoIndex -Maximum ($i + 1) -Random $rng
$temporary = $characters[$i]
$characters[$i] = $characters[$j]
$characters[$j] = $temporary
}
$password = [System.Security.SecureString]::new()
try {
foreach ($character in $characters) {
$password.AppendChar($character)
}
$password.MakeReadOnly()
if (-not $user.Enabled) {
Write-Warning "$AccountName is disabled; its password will still rotate."
}
if ($PSCmdlet.ShouldProcess("$env:COMPUTERNAME\$AccountName", 'Rotate password')) {
Set-LocalUser -Name $AccountName -Password $password -Confirm:$false
[pscustomobject]@{
ComputerName = $env:COMPUTERNAME
AccountName = $user.Name
RotatedAt = (Get-Date).ToString('o')
Result = 'Success'
}
}
}
finally {
$password.Dispose()
$characters.Clear()
$rng.Dispose()
}
The result is assembled directly into a SecureString and passed to Set-LocalUser; it is never converted to a readable string. The account lookup occurs before generation, and the finally block releases the secure string and random-number generator.
Apply and Verify the Rotation
Save the code as Rotate-LocalAdmin.ps1, review it, then run it from an elevated 64-bit PowerShell 5.1 or PowerShell 7 session. Supply a different account name when required: .\Rotate-LocalAdmin.ps1 -AccountName 'ServerAdmin'.
Verify the account state and timestamp with Get-LocalUser -Name 'Administrator' | Select-Object Name, Enabled, PasswordLastSet, PasswordExpires. Password reset does not enable the account, alter local group membership or prove that the secret reached the approved vault, so test recovery separately.
Automate the Rotation Across the Fleet
For fleet use, publish the reviewed script through Intune, Configuration Manager, PDQ Deploy or an equivalent endpoint runner, then execute it as Local System through a scheduled task or platform runbook. Generate the password inside each endpoint session; this avoids sending plaintext credentials across remote administration channels.
Australian mid-market operations often mix vendor appliances, Hyper-V and VMware estates, so stagger changes rather than starting every host together. Schedule around AEST and AEDT using DD/MM/yyyy timestamps, and avoid Sydney and Melbourne business hours during Australian financial-year close.
Preserve Recovery and Auditability
Where Microsoft LAPS already administers the account, use its supported reset process so the encrypted recovery record remains authoritative. This exact script intentionally discards the password and therefore suits only estates with an independent recovery mechanism. For a vault-managed credential, use the vault’s secret-injection process or native LAPS workflow rather than adding a plaintext parameter.
Grant the runner only the permissions needed to change the target account. Review Security logs for password-reset events, retain endpoint and vault timestamps for correlation, and never enable verbose transcript logging around secret generation. Australian privacy and security obligations favour auditable controls without plaintext exposure.
Resolve Common Failure Modes
If Get-LocalUser is unavailable, confirm that 64-bit Windows PowerShell can load the built-in Microsoft.PowerShell.LocalAccounts module. The 32-bit PowerShell path on a 64-bit Windows host cannot load it; run C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe when a legacy policy requires it.
Access denied usually means the process is not elevated, the account is protected by local policy or the target name is wrong. Confirm the RID 500 identity, check password and lockout policies, and inspect the task runner's exit code. Do not retry blindly; distinguish command failures from failed sign-in tests, since only the latter can contribute to local lockout.
Operational Recommendations for Safer Rotation
A controlled rollout depends on consistent prerequisites, timing and evidence rather than on the rotation command alone.
- Confirm each target account, owner and approved recovery method before deployment.
- Execute as Local System through a signed or integrity-controlled deployment channel.
- Keep passwords inside LAPS or a privileged access vault, never in scripts or logs.
- Test the reset and recovery path in a non-production environment first.
- Stagger schedules using Australian Eastern Standard and Daylight Time offsets.
- Record success, failure and drift centrally with machine and account identifiers.
Pilot the workflow on representative servers and appliances, then expand only after recovery has been demonstrated. This produces repeatable rotations while preserving a controlled break-glass route for every endpoint.