PowerShell: run a script as another account with a stored credential
CredentialManager, Get-StoredCredential and Start-Process -Credential to run a script without typing a password.
Run a PowerShell script under another account from a scheduled or automated context, without typing the password: store the credential once in the Windows Credential Manager, then pass it to Start-Process -Credential.
Store the credential
The CredentialManager module provides New-StoredCredential and Get-StoredCredential.
Install-Module CredentialManager
# Prompt once for the account, then store it under a target name
Get-Credential -UserName "DOMAIN\svc_healthcheck" -Message "Health check" | New-StoredCredential -Target "healthcheck-target"
The stored credential is only readable by the Windows user that saved it, so run this step as the account that will later run the job.
Start a script with the stored credential
$cred = Get-StoredCredential -Target "healthcheck-target"
$powershellArguments = "-file D:\scripts\healthcheck.ps1"
Start-Process powershell.exe -ArgumentList $powershellArguments -Credential $cred
Arguments for the script are added after the file name:
$powershellArguments = "-file D:\scripts\healthcheck.ps1", "arg1", "arg2"
The script can also be read from a network share:
$powershellArguments = "-file \\fileserver\share\healthcheck.ps1"
Start-Process powershell.exe -ArgumentList $powershellArguments -Credential $cred
Capture the output and the exit code
# Redirect standard output to a file
Start-Process whoami -RedirectStandardOutput output.txt -Credential $cred
# Wait for the process and read its exit code
$process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru -Wait
$process.ExitCode
Notes
- To read the plain-text password back from a credential object:
$cred.GetNetworkCredential().Password. Avoid it in logs and scripts. - The target account needs access to the script path and to any module it imports. Check
$env:PSModulePathif a module is not found under the other account. - Useful references: storing credentials securely for PowerShell scripts, Start-Process guide.