Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save GeoffWilliams/e8f64a8d01f3c8611e5ef06d5989f4d5 to your computer and use it in GitHub Desktop.

Select an option

Save GeoffWilliams/e8f64a8d01f3c8611e5ef06d5989f4d5 to your computer and use it in GitHub Desktop.
shim.ps1
# shim.ps1
# ========
#
# Run a command as another user
#
# RunAsUser User to become to run the command
# RunAsPassword Password to become the user (SecureString is unusable since we
# are fully automated and can't prompt for a password
# Next command line argument - Program to run
# Rest of command line arguments - Arguments will be passed to program to execute
param(
[string]$RunAsUser,
[String]$RunAsPassword)
$args_wrapped = , "/c" + $args
$bad_invocation = $false
if (! $RunAsUser) {
Write-Error "Must provide a user to run as, eg DEMO\reporting (must be domain user)"
$bad_invocation = $true
}
if (! $RunAsUser) {
Write-Error "Must provide a password for the user, eg 'Password123!'"
$bad_invocation = $true
}
if ($args.Count -lt 1) {
Write-Error "Must specify program to run as first argument"
$bad_invocation = $true
} elseif ($args.Count -lt 2) {
Write-Error "Implausible argument count - need the executable plus all its arguments, eg 'c:\temp\scom2016\setup.exe /silent /install ..."
}
if (! $bad_invocation -and (!(Get-Command $args_wrapped[1] -ErrorAction SilentlyContinue))) {
Write-Error "File Not Found: $($args_wrapped[1])"
$bad_invocation = $true
}
if ($bad_invocation) {
Write-Error "Exiting due to previous failures!"
exit 1
}
Write-Error "DEBUG: become $RunAsUser with supplied password"
$ss= $RunAsPassword | ConvertTo-SecureString -Force -AsPlainText
$c = New-Object System.Management.Automation.PsCredential($RunAsUser,$ss)
Write-Error "DEBUG: Shimming to $($args_wrapped[1])"
Start-Process -WorkingDirectory c:\temp -FilePath "$env:comspec" -Credential $c -ArgumentList $args_wrapped -NoNewWindow -Wait
$status = If ($lastExitCode -ne $null) {$lastExitCode} Else {255}
Write-Error "DEBUG:...finished, status: $status"
exit $status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment