0

I have a jenkinsfile, where I am setting a parameter and wants to use it in another powershell script.

Here is my jenkinsfile

parameters {
        choice( name: 'DeploymentEnvironment',choices: "None\nDev\nQA\nProd",description: 'Deployment Choice')
    }

stage('Publishing to S3') {
    steps {
        withCredentials() {
            echo "${params.DeploymentEnvironment}"
            powershell(". '.\\packages.ps1' ${params.DeploymentEnvironment}")
        }
    }
}
echo "${params.DeploymentEnvironment}" = QA

My packages.ps1 script

...
Write-Output $DeploymentEnvironment
Write-Output $env.DeploymentEnvironment
Write-Output $env:DeploymentEnvironment
Write-Output ($params.DeploymentEnvironment)
...

I am unable to get DeploymentEnvironment=QA here in packages.ps1. Above every Write-Output command is printing nothing.

How can I pass and use DeploymentEnvironment variable declared in Jenkinsfile in my packages.ps1 script.

Thanks.

1
  • I can't tell you how to pass parameters to powershell script, but I can say - ${params.DeploymentEnvironment}" is not correct. To call params in powershell just call it as env: $DeploymentEnvironment Commented Aug 10, 2021 at 10:40

1 Answer 1

1

You need to pass your input parameter as an environment parameter to the PowerShell runtime environment, the easiest way to do so is using the environment directive that is a part of the declarative pipeline syntax, which sets parameters (in addition to default ones) that will be loaded as environments variables to the powershell (or cmd) execution environment.
The environment directive can be used in the pipeline level or in the stage level.
In your case you can use something like:

parameters {
    choice( name: 'DeploymentEnvironment',choices: ['None', 'Dev', 'QA', 'Prod' ,description: 'Deployment Choice')
}
stage('Publishing to S3') {
    environment {
        DEPLOYMENT_ENVIRONMENT = "${params.DeploymentEnvironment}"
    }
    steps {
        withCredentials() {
           echo DEPLOYMENT_ENVIRONMENT
           powershell(". '.\\packages.ps1'") 
           // DEPLOYMENT_ENVIRONMENT will be available as an environment parameter to the powershell script
        }
    }
}

then in your poweshell script use the DEPLOYMENT_ENVIRONMENT parameter.

A different approach will be to modify your powershell script to receive a parameter, and pass the parameter like you are doing now.
Btw, if your are only publishing things to s3 you can use the Pipeline: AWS Steps plugin for this task and avoid the powershell script

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your suggestion has worked for me. I am collecting few more files from different folder and putting it all together in a S3 bucket. So I don't think Pipeline: AWS Steps can work straight away for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.