Groovy Jenkins powershell pipe not working

Viewed 52

I want to replace some text in a file after Jenkins does its build step.

I have the code below in my post build step.

powershell.exe -Command(Get-Content "./PublishedWebsites/app.config") |
Foreach-Object {$_.replace({{MyDummValue}}, "${env.BUILD_NUMBER}")} | 
Set-Content "./PublishedWebsites/app.config"

The first part works (Get-Content "./PublishedWebsites/app.config") up until the pipe ("|").

After the pipe it throws an error that Foreach-Object is not recognized by an internal or external command.

I am thinking it has something to do with the escape sequence and the syntax. So I have tried this as well

"""powershell.exe -Command(Get-Content "./PublishedWebsites/app.config") |
    Foreach-Object {$_.replace({{MyDummValue}}, "${env.BUILD_NUMBER}")} | 
    Set-Content "./PublishedWebsites/app.config"""

Then for some reason jenkins is trying to evaluate the $_.replace({{MyDummValue}} before the post build step is even reached and gives me the error of 'Cannot get property replace on null object'

So I am at a loss. All I want to do is on a post build step, rename a value in a file with the Build Number.

1 Answers

When calling PowerShell (or other) scripts from Groovy, always use single-quoted (or triple-single-quoted) string literals for the script. With double-quoted (or triple-double-quoted) strings, Groovy tries to interpolate the string, so you'd have to escape $ as \$, to use it literally. While this is just a nuisance, double-quoted strings are also prone to script injection, where a pipeline user might run arbitrary PowerShell scripts, when pipeline parameters are interpolated by Groovy within the script.

Another mistake: the value {{MyDummValue}} isn't quoted.

Also, I don't know why you are calling powershell.exe explicitly. Use the powershell step instead:

post {
    always {  // or one of the other available sections
        powershell '''
            Get-Content "./PublishedWebsites/app.config" |
                Foreach-Object {$_.replace("{{MyDummValue}}", $env:BUILD_NUMBER)} |
                Set-Content "./PublishedWebsites/app.config"
        '''
    }
}
Related