$cs.UsrMgr_ChangePassword
Description
Section titled “Description”Changes the password of a local user account. If the specified user does not exist, the function returns silently without error. If Windows rejects the new password — for example, because it doesn’t meet the password policy — the function doesn’t throw an exception either, so test the password on a client before you deploy.
Syntax
Section titled “Syntax”$cs.UsrMgr_ChangePassword(string userName, string password)
Parameters
Section titled “Parameters”userName (String)
Section titled “userName (String)”Name of the local user whose password will be changed. If the user does not exist, no error is raised.
password (String)
Section titled “password (String)”The new password, in clear text.
Return value
Section titled “Return value”None.
Example
Section titled “Example”Rotate a local service account’s password as part of an application upgrade:
if ($cs.UsrMgr_ExistLocalUserAccount('administrator')) { $cs.Job_WriteLog("Changing password for administrator") $cs.UsrMgr_ChangePassword('administrator', 'VerySuperSecretPassw0rd!')}Generate a random password of letters and digits, store it in a variable, and apply it to a service account before restarting the service that runs under it:
$chars = [char[]]'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'$newPassword = -join (1..20 | ForEach-Object { $chars | Get-Random })
if ($cs.UsrMgr_ExistLocalUserAccount('svc_capaagent')) { $cs.Job_WriteLog("Rotating password for svc_capaagent") $cs.UsrMgr_ChangePassword('svc_capaagent', $newPassword) Set-Service -Name 'CapaAgentService' -Credential (New-Object System.Management.Automation.PSCredential('svc_capaagent', (ConvertTo-SecureString $newPassword -AsPlainText -Force))) Restart-Service -Name 'CapaAgentService' -Force}