0

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Karthik
  • 97
  • 2
  • 3
  • 10

2 Answers2

2

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
Avshalom
  • 8,657
  • 1
  • 25
  • 43
  • Hi @Avshalom, thanks for fixing the script. It works great when run locally. However, because Jenkins doesn't allow any popups, it prevents the script from getting executed. I tried '-WindowStyle Hidden' to the -ArgumentList but it errors out with the following: **Parameter set cannot be resolved using the specified named parameters** – Karthik Sep 10 '15 at 02:31
  • 1
    Jenkins labels the build as Success but eventviewer has this error under system log: **Application popup: powershell.exe - Application Error : The application was unable to start correctly (0xc0000142). Click OK to close the application**. Any idea how I can suppress that little black command window from getting spooned? - Thanks. – Karthik Sep 10 '15 at 02:34
-1

Try this:

Start-Process powershell -WindowStyle 'Hidden' -ArgumentList '-executionpolicy', 'bypass', '-file', $scriptFullName -Credential $C
Noam Hacker
  • 4,671
  • 7
  • 34
  • 55