/
/

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

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: Microsoft.Graph, Az.KeyVault
  • Administrative rights on all target machines

Task 1: Configure Azure Key Vault for password storage

📌 Use Case:

This task is to establish Azure Key Vault configurations that support robust security, including firewall restrictions, private endpoints, HSM protection, and detailed logging.

  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. Create a secret placeholder named AdminPassword–<deviceName> with an empty value; PowerShell will populate it later.

Task 2: Create a PowerShell script to rotate passwords

📌 Use Case:

This task updates the local admin password and securely stores it in Key Vault (generating a new version if existing). It can be deployed via Azure Automation, Task Scheduler, Intune script deployment, or NinjaOne for wide-scale distribution across endpoints.

  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:

$DeviceName = $env:COMPUTERNAME

$AdminUser = "localadmin"

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

net user $AdminUser $NewPassword

Connect-AzAccount -Identity

$VaultName = "MySecureVault"

$SecretName = "AdminPassword-$DeviceName"

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

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

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"

$Secret = Get-AzKeyVaultSecret -VaultName $VaultName -Name "AdminPassword-$DeviceName"

$SecretValue = $Secret.SecretValueText

  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 is used to verify 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 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:

You might also like

Ready to simplify the hardest parts of IT?