My9to5
My9to5

Reputation: 93

How can I execute a line of code as another user?

For testing, I'd like to output the execution of the line:

.\pgpwde --status --disk 0

to a text file, simply for testing and eventually integrate into a loop. But the text file just shows up blank. Also, when running the called powershell window, it just disappears even with the -noexit switch.

$Setloc = set-location "C:\Program Files (x86)\PGP Corporation\PGP Desktop"

$username = 'DOMAIN\Username'
$Password = 'PASSWORD' | ConvertTo-SecureString -Force -AsPlainText
$credential = New-Object System.Management.Automation.PsCredential($username, $Password)

Start-Process powershell.exe -Credential $credential -ArgumentList '$Setloc', "/C", ".\pgpwde --status --disk 0" | out-file "C:\users\USERNAME\Desktop\test.txt" 

Upvotes: 1

Views: 207

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 61293

Hope all comments make sense, if something isn't clear let me know.

  • $Setloc = Set-location "C:\Program Files (x86)\PGP Corporation\PGP Desktop" This is being executed not stored as an expression.
  • In -ArgumentList, '$Setloc' Single quotes are not allowing variable expansion here. No quotes are needed for variables.
  • $credential The construction of your credential object is fine, though, you should use -ArgumentList $username, $Password instead of ($username, $Password). See this answer for more details. Also, are you sure this user can execute commands on your local host?

Try this instead:

$myCommand = "'C:\Program Files (x86)\PGP Corporation\PGP Desktop\pgpwde' --status --disk 0"

$username = 'DOMAIN\Username'
$Password = ConvertTo-SecureString -String 'PASSWORD' -Force -AsPlainText
$credential = New-Object System.Management.Automation.PsCredential -ArgumentList $username, $Password

$expression = @"
    try
    {
        & $myCommand | Out-File `$env:USERPROFILE\Desktop\test.txt -Force
    }
    catch
    {
        `$_.Exception.Message | Out-File `$env:USERPROFILE\Desktop\ERROR.txt -Force
    }
"@

# Note: Both, your program's output as well as if there are any errors, will be stored on
#       $username's profile in the Desktop folder.

Start-Process powershell.exe -ArgumentList "-c $expression" -Credential $credential

Thanks mklement0 for the helpful feedback.

Upvotes: 2

Related Questions