Question:
I have been trying to run a script from a Windows Jenkins (slave) server. The script is written in PowerShell and requires elevated privileges (such as if one right-clicked on PS and selected run-as-administrator).
Jenkins launches its scripts the following way:
1 2 |
powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\JOHAN.DER\AppData\Local\Temp\2\hudson9084956499652818911.ps1'" |
My script fails because it requires elevated privileges. How can I spawn a new elevated-privileged PS process (that does not require clicking because Jenkins can’t do that) that could run my script?
Cheers!
Answer:
The snippet below checks if current process is elevated and if not, it spawns a new, privileged process. It is little tricky to get output of the child powershell process, so I’m using transcript command to capture it. Below you can find my pipeline definition step:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
powershell """ cd "${env.WORKSPACE}" If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { echo "* Respawning PowerShell child process with elevated privileges" \$pinfo = New-Object System.Diagnostics.ProcessStartInfo \$pinfo.FileName = "powershell" \$pinfo.Arguments = "& '" + \$myinvocation.mycommand.definition + "'" \$pinfo.Verb = "RunAs" \$pinfo.RedirectStandardError = \$false \$pinfo.RedirectStandardOutput = \$false \$pinfo.UseShellExecute = \$true \$p = New-Object System.Diagnostics.Process \$p.StartInfo = \$pinfo \$p.Start() | Out-Null \$p.WaitForExit() echo "* Child process finished" type "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt" Remove-Item "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt" Exit \$p.ExitCode } Else { echo "Child process starting with admin privileges" Start-Transcript -Path "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt" } # put rest of your script here, it will get executed # with elevated privileges. """ |