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:
| Task | Purpose |
| Task 1: Configure Azure Key Vault for password storage | Set up secure, centralized storage for local admin passwords using Azure Key Vault |
| Task 2: Create a PowerShell script to rotate passwords | Automate secure password generation and rotation using custom PowerShell scripts |
| Task 3: Secure and restrict password access | Limit 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 Policy | Ensure secure local password configurations are consistently applied via GPO |
| Task 7: Validate password rotation using CMD and PowerShell | Run 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.
- Go to Key Vaults > Create, and set the resource group and region.
- Under Access Policies, grant service accounts or automation users permissions like Set, Get secrets.
- Enable Soft delete and Purge protection for retention safety.
- Optionally, use RBAC instead of access policies for access control and auditable assignments.
- 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)
- Open PowerShell as an administrator. Press the Windows key, type PowerShell, then right-click Windows PowerShell and select Run as administrator.
- 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.
- Limit access using RBAC roles (e.g., Reader, Secret Reader) or Access Policies.
- Enable logging via Azure Monitor or Diagnostic Settings to track secret retrieval activity.
- Use Key Vault Private Endpoints to restrict access over the Azure backbone instead of exposing it over the public internet.
- 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.
- Open PowerShell as an administrator. Press the Windows key, type PowerShell, then right-click Windows PowerShell and select Run as administrator.
- 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.
- 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.
- Open PowerShell as an administrator. Press the Windows key, type PowerShell, then right-click Windows PowerShell and select Run as administrator.
- 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.
- 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.
- Navigate to: Computer Configuration > Windows Settings > Security Settings > Account Policies > Password Policy
- 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.
- Open Command Prompt or PowerShell.
- Run the following commands:
| Validation Task | CMD Command | PowerShell Command |
| Check recent password change events | wevtutil qe Security "/q:*[System[(EventID=4723)]]" /c:3 /f:text | Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4723} -MaxEvents 3 | Format-List |
| List local users | net user | Get-LocalUser |
| Test DNS resolution for Key Vault | nslookup <yourvaultname>.vault.azure.net | Resolve-DnsName -Name "<yourvaultname>.vault.azure.net" |
| Check Task Scheduler job status | schtasks /query /tn "RotateLocalAdminPassword" | Get-ScheduledTask -TaskName "RotateLocalAdminPassword" |
Things to look out for
| Risks | Potential Consequences | Reversals |
| Script fails to update the password | The 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 Vault | Causes loss of access to credentials, especially during recovery scenarios | Enable error handling and confirmation logging; validate Key Vault write access before rotation. |
| Key Vault access misconfigured | Unauthorized 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 enforced | Passwords may remain unchanged for long periods, violating security policies | Use scheduled tasks with regular interval enforcement; monitor registry key or audit logs for confirmation. |
| Time sync issues across endpoints | May affect scheduled task timing or create false assumptions in audit logs | Sync 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 service | What it is | How it helps with secure local admin password rotation |
| Script deployment | Push PowerShell scripts to rotate local passwords securely on endpoints | Ensures consistent and automated password rotation across all managed devices |
| Rotation monitoring | Track when devices last changed their password via registry keys or script logs | Helps verify that rotation is occurring as scheduled and flags any missed or failed attempts |
| Key Vault integration | Automate Key Vault communication using managed identities or credentials | Allows passwords to be securely stored and retrieved during rotation without hardcoded secrets |
| Alerting and auditing | Notify technicians when rotation fails or when passwords are nearing expiration | Provides visibility and accountability for password rotation success or failure |
| Cross-tenant scalability | Maintain 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:

