Skip to content

Instantly share code, notes, and snippets.

@nklbdev
Created July 21, 2023 18:49
Show Gist options
  • Save nklbdev/96ba2b7217c7665d7eb2fa99cca8f480 to your computer and use it in GitHub Desktop.
Save nklbdev/96ba2b7217c7665d7eb2fa99cca8f480 to your computer and use it in GitHub Desktop.
PowerShell script to run a command as another user with saved credentials
# Usage:
#
# Call it without any args except path to file to save credential.
# The script will show a window for entering credentials and save them to a file in encrypted form.
# > powershell -File run_as_with_saved_creds.ps1 creds.txt
#
# Call it with arguments after path to file with saved credential.
# The script will execute the command as the user whose credentials have been saved in the file.
# > powershell -File run_as_with_saved_creds.ps1 creds.txt some commands and args
function QuotePathWithWhitespaces([string]$Path) {
if ($Path -match '.*\s.*')
{ """$Path""" } else { $Path }
}
function GetAndSaveCredential([string]$Path) {
$Credential = Get-Credential
Set-Content `
-Path $Path `
@(
$Credential.UserName,
($Credential.Password | ConvertFrom-SecureString)
)
$Credential
}
function LoadCredential([string]$Path) {
$CredFileContent = Get-Content -Path $Path
New-Object System.Management.Automation.PsCredential(
$CredFileContent[0],
($CredFileContent[1] | ConvertTo-SecureString))
}
if ($args.Length -eq 0)
{
"Specify path to credential file at first argument"
exit
}
$CredPath = $args[0]
if ($args.Length -eq 1)
{
GetAndSaveCredential($CredPath)
exit
}
$args
$Credential = LoadCredential($CredPath)
$QuotedArgs = $args | Select-Object -Skip 2 | ForEach-Object { QuotePathWithWhitespaces($PSItem) }
$ps = Start-Process `
-PassThru `
-WindowStyle Hidden `
-Credential $Credential `
-FilePath $args[1] `
-ArgumentList $QuotedArgs
$ps.WaitForExit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment