We have a requirement to launch PowerShell scripts via a product called Jenkins and have run into an issue. I have been assisting my colleague in resolving this issue and note the issue also occurs when running the script/s using an alternative scheduler e.g. Windows Task Scheduler. Therefore the issue is not directly related to Jenkins is appears to be a generic issue as explained in detail below.
I have boiled the issue down, and found it occurred when you combine the following
1: -credential parameter i.e. type System.Management.Automation.PSCredential
2: non manual execution of the script/s (e.g. via Windows Task Scheduler etc. as noted above)
I have explained the issue below using a couple of basic scripts (not production scripts) which demonstrate the exact nature of the issue.
If you have two script as follows (the below just demonstrates the issue)
#Script1
$cred_password = ConvertTo-SecureString “Pa$$w0rd” -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist “Domain\UserB”, $cred_password
try {
start-process C:\Windows\SYSTEM32\WindowsPowerShell\v1.0\powershell.exe -ArgumentList ‘-noprofile -executionpolicy bypass -file C:\temp\script2.ps1’ -Credential $cred -ErrorAction Stop
}catch{$Error[0] | Out-File “C:\temp\error.txt” -Force}
Then you have another script
#script2
Get-Service | Out-File C:\temp\Services3.txt -Force -Confirm:$false
Now if you open a PowerShell command prompt as UserA (e.g. not the one in the above $Cred) and run C:\temp\script1.ps1 it works no worries e/g/ script1 runs and the start-process with the -credential executes script2 as UserB (the point here being you are running manually)
However as soon as you add script1 to a scheduler let’s use Windows Task Scheduler and run Script1 as a scheduled task under user ID UserA (weather they are logged in or not) the scheduled tasks runs Script1 but does not appear to run Script2 and can see no errors returned.
If you then remove the -credential from the Start-Process cmdlet and let the scheduler run it again it works. (However in reality UserB would have higher rights which is the point of using the –credential parameter)
Therefore appears to be a combination of using a credential object when running from a scheduler (as running manually always works).
I need assistance in resolving this issue or finding a practical workaround (cause and resolution would be better)
The same issue appears swapping out start-process with invoke-command (different commands) and again using the -credential parameter e.g. runs manually but not via unattended method
Thanks All
AZUser