Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elevated PS script in Jenkins

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:

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!

like image 606
Peter Avatar asked Nov 08 '22 05:11

Peter


1 Answers

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:

            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.
            """
like image 111
Marek Obuchowicz Avatar answered Nov 14 '22 21:11

Marek Obuchowicz