/
/

How to Rotate Local Admin Passwords Securely Using PowerShell and Azure Key Vault

by Miguelito Balba, IT Editorial Expert
How to Rotate Local Admin Passwords Securely Using PowerShell and Azure Key Vault blog banner image
How to Rotate Local Admin Passwords Securely Using PowerShell and Azure Key Vault blog banner image

Key Points

  • Automate password changes with Azure Key Vault and PowerShell to remove the risk of stale, manually managed local admin credentials.
  • Store every rotated password as a versioned secret in Key Vault instead of a shared spreadsheet or ticket.
  • Restrict who can retrieve a stored password using role-based access control (RBAC) roles, Key Vault Private Endpoints, and logged access.
  • Track each device’s last rotation date in the registry to confirm the schedule is running.
  • Back up automation with a Group Policy password baseline so manual fallback logins stay compliant.
  • Rotate every 30 to 90 days, depending on your compliance framework, and rotate immediately after any credential exposure.

Using automation to rotate local admin passwords is a crucial step in risk reduction. The risks, which primarily target security, are commonly introduced when credentials are managed manually. Thanks to PowerShell and Azure Key Vault, the automation process becomes streamlined, ensuring strong security, compliance, and audibility by eliminating the human element and securely managing credentials.

The main goals of this method are to rotate passwords periodically across devices, store passwords securely in Azure Key Vault, audit access and retrieval activity, and comply with Zero Trust and LAPS-aligned best practices. In this guide, we will walk you through setting up Azure Key Vault, scripting password rotation, enforcing security controls, and validating compliance across endpoints.

At a glance:

TaskPurpose
Task 1: Configure Azure Key Vault for password storageSet up secure, centralized storage for local admin passwords using Azure Key Vault
Task 2: Create a PowerShell script to rotate passwordsAutomate secure password generation and rotation using custom PowerShell scripts
Task 3: Secure and restrict password accessLimit access to stored credentials using Key Vault RBAC, managed identities, or PIM
Task 4: Retrieve passwords securely (optional admin recovery)Allow authorized recovery of local passwords via secure PowerShell retrieval methods
Task 5: Use Registry to track rotation time or metadata (optional)Store timestamp or metadata in the Windows registry to verify or audit password changes
Task 6: Enforce password policies via Group PolicyEnsure secure local password configurations are consistently applied via GPO
Task 7: Validate password rotation using CMD and PowerShellRun system-level commands to verify password changes and check system access status

Prerequisites for automating local admin passwords rotation

Before proceeding with the tasks, make sure your environment meets the following requirements:

  • An Azure subscription with an Azure Key Vault provisioned (Azure Key Vault is a secure secrets store for passwords, keys, and certificates, backed by hardware-level encryption, supporting Zero Trust and least-privilege principles.)
  • Azure AD–joined or hybrid-joined devices
  • A known local administrator account (e.g., “localadmin”)
  • PowerShell remoting enabled
  • Installed modules: Accounts, Az.KeyVault
  • Administrative rights on all target machines

Task 1: Configure Azure Key Vault for password storage

Use Case:

This task provisions the Azure Key Vault and sets its access model so only authorized identities can write and read stored passwords, and turns on retention protections so a rotated secret can’t be permanently lost.

Network restrictions like firewall rules and Private Endpoints, plus audit logging, are configured in Task 3. Secrets are encrypted with an HSM-backed key by default, so no separate HSM setup is needed here.

  1. Go to Key Vaults > Create, and set the resource group and region.
  2. Under Access Policies, grant service accounts or automation users permissions like Set, Get secrets.
  3. Enable Soft delete and Purge protection for retention safety.
  4. Optionally, use RBAC instead of access policies for access control and auditable assignments.
  5. Decide on a secret-naming convention, such as AdminPassword-<deviceName>.

Note: You don’t need to pre-create the secret as Task 2’s script creates it automatically the first time it rotates a password.

Task 2: Create a PowerShell script to rotate passwords

Use Case:

This task generates a new local admin password, saves it to Key Vault, and only then applies it locally so a Key Vault write never leaves a device with a password that isn’t recoverable. It can be deployed via Azure Automation, Task Scheduler, Intune script deployment, or NinjaOne for wide-scale distribution, but the authentication method below only works on certain deployment targets. (See the note after the script)

  1. Open PowerShell as an administrator. Press the Windows key, type PowerShell, then right-click Windows PowerShell and select Run as administrator.
  2. Run the following command:

# Windows PowerShell 5.1

Add-Type -AssemblyName System.Web

$DeviceName = $env:COMPUTERNAME

$AdminUser = "localadmin"

$VaultName = "MySecureVault"

$SecretName = "AdminPassword-$DeviceName"

$NewPassword = [System.Web.Security.Membership]::GeneratePassword(20,4)

# Step 1: Save the new password to Key Vault BEFORE changing it locally.

try {

Connect-AzAccount -Identity -ErrorAction Stop

Set-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName `

-SecretValue (ConvertTo-SecureString $NewPassword -AsPlainText -Force) `

-ErrorAction Stop

}

catch {

Write-Error "Key Vault write failed for $DeviceName — local password was NOT changed. $_"

exit 1

}

# Step 2: Only apply the new password locally after Key Vault confirms the write.

try {

net user $AdminUser $NewPassword

if ($LASTEXITCODE -ne 0) { throw "net user returned exit code $LASTEXITCODE" }

}

catch {

Write-Error "Local password change failed for $DeviceName AFTER the new password was already saved to Key Vault. The stored secret and the live local password are now out of sync — investigate manually. $_"

exit 1

}

Write-Output "Password rotation completed successfully for $DeviceName."

Since System.Web isn’t available for PowerShell 7, below is a substitute script you can use for PowerShell 7:

function New-RandomPassword {
    param([int]$Length = 20, [int]$MinNonAlphanumeric = 4)
    $alphaNum = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    $symbols  = '!@#$%^&*()-_=+[]{}'
    $nonAlphaCount = Get-Random -Minimum $MinNonAlphanumeric -Maximum ($Length - $MinNonAlphanumeric)
    $chars  = 1..($Length - $nonAlphaCount) | ForEach-Object { $alphaNum[(Get-Random -Maximum $alphaNum.Length)] }
    $chars += 1..$nonAlphaCount             | ForEach-Object { $symbols[(Get-Random -Maximum $symbols.Length)] }
    -join ($chars | Sort-Object { Get-Random })
}
$NewPassword = New-RandomPassword -Length 20 -MinNonAlphanumeric 4

Note: Connect-AzAccount -Identity needs a managed identity from Azure’s Instance Metadata Service, so it only works on Azure resources, such as Azure Automation, Azure VMs, or Arc-enabled servers.

Task 3: Secure and restrict password access

Use Case:

This task limits Azure Key Vault access to designated recovery personnel using RBAC roles, ensuring only authorized users can retrieve local admin passwords during emergencies.

Follow these best practices to secure your Azure Key Vault secrets to enforce least privilege access and support auditing and incident response efforts.

  1. Limit access using RBAC roles (e.g., Reader, Secret Reader) or Access Policies.
  2. Enable logging via Azure Monitor or Diagnostic Settings to track secret retrieval activity.
  3. Use Key Vault Private Endpoints to restrict access over the Azure backbone instead of exposing it over the public internet.
  4. Grant retrieval access only to designated automation accounts or authorized personnel performing recovery operations.

Task 4: Retrieve passwords securely (optional admin recovery)

Use Case: 

This task is used in recovery scenarios where administrators may need to retrieve a local admin password from Key Vault.

  1. Open PowerShell as an administrator. Press the Windows key, type PowerShell, then right-click Windows PowerShell and select Run as administrator.
  2. Run the following command:

Connect-AzAccount -Identity

$VaultName = "MySecureVault"

$DeviceName = "LAPTOP-1234"

$SecretValue = Get-AzKeyVaultSecret -VaultName $VaultName -Name "AdminPassword-$DeviceName" -AsPlainText

Note: -Identity only works where a managed identity exists. If an administrator is running this interactively on their own workstation, use Connect-AzAccount instead, and ensure their account has the Key Vaults Secrets User role.

  1. Remember to:
    • Log all retrieval events
    • Use retrieval only in emergency or authorized recovery workflows
    • Rotate the password immediately after retrieval if needed

Task 5: Use Registry to track rotation time or metadata (optional)

Use Case: 

This task verifies that password rotation has occurred on a device. You can track the last rotation timestamp using the Windows Registry.

  1. Open PowerShell as an administrator. Press the Windows key, type PowerShell, then right-click Windows PowerShell and select Run as administrator.
  2. Run the following command:

New-ItemProperty -Path "HKLM:\SOFTWARE\Org\AdminPasswordRotation" `

-Name "LastRotation" -PropertyType String -Value (Get-Date).ToString("u") -Force

Task 6: Enforce password policies via Group Policy

Use Case:

This task ensures password complexity even during manual fallback scenarios. It enforces compliance and guarantees consistency across your organization’s credential policy, even outside automated rotations.

  1. Open the Group Policy as an administrator. Press the Windows key, type gpedit.msc, then press Ctrl + Shift + Enter to run it as an administrator.
  2. Navigate to: Computer Configuration > Windows Settings > Security Settings > Account Policies > Password Policy
  3. Set the following:
    • Minimum password length = 20 characters
    • Password must meet complexity requirements = Enabled
    • Maximum password age = 30 days

Task 7: Validate password rotation using CMD and PowerShell

Use Case:

This task utilizes the Command Prompt and PowerShell to help confirm that automation is functioning and passwords are being updated regularly.

  1. Open Command Prompt or PowerShell.
  2. Run the following commands:
Validation TaskCMD CommandPowerShell Command
Check recent password change eventswevtutil qe Security "/q:*[System[(EventID=4723)]]" /c:3 /f:textGet-WinEvent -FilterHashtable @{LogName='Security'; Id=4723} -MaxEvents 3 | Format-List
List local usersnet userGet-LocalUser
Test DNS resolution for Key Vaultnslookup <yourvaultname>.vault.azure.netResolve-DnsName -Name "<yourvaultname>.vault.azure.net"
Check Task Scheduler job statusschtasks /query /tn "RotateLocalAdminPassword"Get-ScheduledTask -TaskName "RotateLocalAdminPassword"

Things to look out for

RisksPotential ConsequencesReversals
Script fails to update the passwordThe password remains unchanged, leaving the endpoint vulnerable to brute-force or reused credentials.Add logging to confirm execution; test scripts manually before automation; monitor Task Scheduler history.
Password is updated, but not saved to Key VaultCauses loss of access to credentials, especially during recovery scenariosEnable error handling and confirmation logging; validate Key Vault write access before rotation.
Key Vault access misconfiguredUnauthorized users may access credentials, or the rotation script fails due to denied access.Review RBAC and Key Vault policies regularly; restrict secrets access to a privileged group only.
Rotation interval not enforcedPasswords may remain unchanged for long periods, violating security policiesUse scheduled tasks with regular interval enforcement; monitor registry key or audit logs for confirmation.
Time sync issues across endpointsMay affect scheduled task timing or create false assumptions in audit logsSync time via NTP; use a centralized log or SIEM for consistent timestamp validation.

Additional considerations for automated local admin password rotation

  • Azure Key Vault limits: Consider naming limits and request throttling if managing hundreds of secrets.
  • Never log passwords: Never log passwords to file or console; always use secure strings.
  • Rotation frequency: Recommend every 30–90 days, depending on the compliance framework.
  • Multi-tenant management: Use tags or resource groups to separate client vaults for MSP environments

NinjaOne services for configuring local admin password rotation

NinjaOne and its tools can help enhance the management of local admin passwords through these services.

NinjaOne serviceWhat it isHow it helps with secure local admin password rotation
Script deploymentPush PowerShell scripts to rotate local passwords securely on endpointsEnsures consistent and automated password rotation across all managed devices
Rotation monitoringTrack when devices last changed their password via registry keys or script logsHelps verify that rotation is occurring as scheduled and flags any missed or failed attempts
Key Vault integrationAutomate Key Vault communication using managed identities or credentialsAllows passwords to be securely stored and retrieved during rotation without hardcoded secrets
Alerting and auditingNotify technicians when rotation fails or when passwords are nearing expirationProvides visibility and accountability for password rotation success or failure
Cross-tenant scalabilityMaintain separate rotation policies and vault storage per customer environment.Enables secure and isolated management of credentials for MSPs handling multiple clients

Rotating local admin passwords for security

With the ever-evolving sophistication of cyber attacks, it’s crucial to establish strategies to protect vital credentials such as local admin passwords. While rotating local admin passwords can be done manually, automation can significantly enhance security. This guide should help you:

  • Configure Azure Key Vault for secure password storage
  • Use PowerShell to rotate and store local administrator credentials
  • Enforce password policies and track rotation
  • Restrict and audit access using RBAC and logging
  • Validate rotation status using built-in Windows tools

Executing these tasks involves following best practices for efficiently employing local admin password rotation. This should aid IT administrators and MSPs in strengthening endpoint security and maintaining operational control across their managed environments.

Related topics:

FAQs

Azure Key Vault has no monthly storage fee for secrets; instead, it bills per operation at roughly $0.03 per 10,000 transactions for operations, such as password storage and retrieval. That totals a few dollars a month, even across a large device fleet.

A Microsoft LAPS deployment can support Microsoft Entra ID-joined devices at no extra cost, built into Windows 10, 11, and Server 2019 and later. Key Vault and PowerShell are worth using instead when you need to centralize secrets alongside other Key Vault credentials, or cover platform LAPS doesn’t manage.

The script’s managed identity needs a write role, such as Key Vault Secrets Officer, to save new passwords. A separate recovery identity should be assigned a read-only role, such as Key Vault Secrets User, so a compromised recovery account can’t overwrite stored passwords.

No, Key Vault doesn’t log access anywhere by default. You need to enable the AuditEvent diagnostic setting first, after which each retrieval appears as a SecretGet event you can query and alert on in Log Analytics.

Yes, it works on servers the same way it does on workstations, since it depends on PowerShell and network access rather than device type. For on-premises or hybrid servers at scale, Microsoft’s newer LAPS for Azure Arc also offers native, policy-based rotation worth evaluating.

You might also like

Ready to simplify the hardest parts of IT?