LLI Wiki — My Digital Knowledge Base

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

Mastodon LLIMastodon SocialFosstodon