在 Powershell 脚本中传递 Jenkins 环境变量

Ram*_*sad 5 declarative jenkins jenkins-pipeline

我想在 powershell 脚本中使用 jenkins 环境变量。这里 ${destination} 在 powershell 脚本中为空。无法确定我在做什么错误。请帮忙

!/bin/groovy

管道{

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()         
    }   
Run Code Online (Sandbox Code Playgroud)

}

tow*_*wel 9

您可以使用以下两种方法之一来解决此问题,以最适合您的为准:

  1. 使用 """ 而不是 ''' 以便能够destination用它的值替换。使用这种方法时,您应该转义 Powershell 的变量标识符以避免不必要的替换,如下所示:\$destinationPath = "${destination}"

  2. 将您的 Jenkins 变量导出为环境变量: withEnv(["DESTINATION=$destination"]) { powershell ''' $destinationPath ="$env:DESTINATION" ... ''' }