Home > Enterprise >  Unable to properly pass arguments with spaces to a PowerShell script from Jenkins
Unable to properly pass arguments with spaces to a PowerShell script from Jenkins

Time:11-24

I have a stage in a Jenkins pipeline where I call a PowerShell script which I do within a container and I call it like this:

    stage('Processing') {
            container('remote') {
                sh "pwsh -file script.ps1 ${params.NAME} ${params.DESCRIPTION} ${params.PEOPLE} 
            }
    }

Within the script I do some preparation for a remote session and I call it using this command

Invoke-Command -Session $RemoteSession -ArgumentList $parameters -ScriptBlock $ScriptBlock

The mentioned preparation is basically me adding another parameter to args which I do like this

    $parameters = @()
    $parameters = $parameters   $args
    $parameters  = $var

Within the scriptblock I reference the args by their index like $args[1]. These are primarily strings, and everything works when an argument passed from Jenkins has no spaces in it. But when let's say ${params.NAME} has a space in it, but the indexing does not work correctly as spaces separate the original string into multiple arguments, hence the if the original index was $args[1], instead of taking in the value of ${params.DESCRIPTION}, it takes in a part of ${params.NAME}.

Do you know how to avoid this issue and take in the parameters with the original indexing even if it has spaces in it?

CodePudding user response:

  • To make PowerShell see the expanded values such as ${params.NAME} as a single argument each, enclose them in ", which in the context of the "..." Groovy string must be escaped as \"

Therefore:

sh "pwsh -File script.ps1 \"${params.NAME}\" \"${params.DESCRIPTION}\" \"${params.PEOPLE}\""
  • Related