How do I execute a PS1 file as a different user?

Karthik picture Karthik · Sep 9, 2015 · Viewed 18.3k times · Source

I need to be able to run a PowerShell script remotely (via Jenkins) as a different user. Since it will be executed as a Jenkins job, Get-Credential is not an option for me. Below is the script I have created but it simply does not work.

$uname='domain\username'
$pwd='password'
$passw=Convertto-SecureString -String $pwd -AsPlainText -force
$mycred=New-object -TypeName System.Management.Automation.PSCredential -ArgumentList $uname, $passw

Invoke-Command -FilePath "C:\test_scripts\fetchquery.ps1" -Authentication default -Credential $mycred -computername localhost

Answer

Avshalom picture Avshalom · Sep 9, 2015

Create a Credential Object:

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

In your code you execute it on localhost, So Start Powershell session Using the Saved credential:

Start-Process powershell -argumentlist '-executionpolicy','bypass','-file',"C:\test_scripts\fetchquery.ps1"' -Credential $credential 

And To run the script Remotely (Don't use Localhost)

Invoke-Command -Computername 'Computer' `
-FilePath C:\test_scripts\fetchquery.ps1 -ArgumentList PowerShell `
-Cred $Credential