Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Jenkins environment variable in Powershell script

i would like to use a jenkins environment variable inside a power shell script.Here ${destination} is coming as null inside powershell script.Not able to identify what is the mistake i am doing.Please help

# !/bin/groovy
pipeline {
    
    agent {
        label {
            label ""
            customWorkspace "C:\\Jenkins\\workspace"
        }
    }
    environment {       
        
        def destination=''
    }
    options {
        timestamps()
        timeout(time: 60, unit: 'MINUTES')      
        skipDefaultCheckout(true)
        disableConcurrentBuilds()
     }
    
    stages {
        
        stage('TEST') 
        {     
            steps {
                    script{
                        destination="\\\\SERVERNAME\\d\$"
                    }
                    echo "${destination}"
                    
                    powershell '''
                    
                        $destinationPath ="${destination}"
                         
                        write-host $destinationPath
                        
                        write-host "test3" '''
                    
                }  
        }
    }
    post {
        always {
            deleteDir()         
        }   
}
like image 711
Ramprasad Avatar asked May 26 '18 21:05

Ramprasad


People also ask

How do you call an environment variable in Jenkins pipeline script?

It is by using the env variable directly in the script block. We can define, let us say, USER_GROUP and display it. You will see that the underlying shell also has access to this environment variable. You can also set an environment variable using withEnv block.


1 Answers

You can resolve this using either one of two methods, whichever suits you best:

  1. Use """ instead of ''' to be able to substitute destination with its value. When using this approach you should escape Powershell's variable identifiers to avoid unwanted substitutions, like so: \$destinationPath = "${destination}"

  2. Export your Jenkins variables as environment variables: withEnv(["DESTINATION=$destination"]) { powershell ''' $destinationPath ="$env:DESTINATION" ... ''' }

like image 54
towel Avatar answered Sep 19 '22 19:09

towel