I read a while ago that you could validate a Jenkinsfile with a curl command, so I though that maybe I could write a simple Powershell script to do the same, just for practice.

The bash version (from Jenkins documentation )

# curl (REST API)
# Assuming "anonymous read access" has been enabled on your Jenkins instance.
# JENKINS_URL=[root URL of Jenkins master]
# JENKINS_CRUMB is needed if your Jenkins master has CRSF protection enabled as it should
JENKINS_CRUMB=`curl "$JENKINS_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)"`
curl -X POST -H $JENKINS_CRUMB -F "jenkinsfile=<Jenkinsfile" $JENKINS_URL/pipeline-model-converter/validate

It turned out not to be that simple. Although I found couple of examples on how to POST files with Invoke-WebRequest, I didn’t get those to work. There were of course other parts of those scripts which were helpful to learn from, but the the call to Invoke-WebRequest always returned No jenkinsfile specified.

The examples I found all set the -ContentType argument to some values and I didn’t think of it much further.

To make a short story even shorter the reason it took a way longer that it should was mainly because I didn’t read the help page for Invoke-WebRequest as thoroughly as I should have. The part that I missed was:

-ContentType

… If this parameter is omitted and the request method is POST, Invoke-WebRequest sets the content type to application/x-www-form-urlencoded. …

Of course I didn’t try that value for -ContentType when I looked at the different examples. But when I changed it (or removed it) it all worked flawlessly.

The end result was something similar to (not the whole script):

# $jenkinsUrl = Url to jenkins
# $FilePath is path to jenkinsfile
# Set credentials etc in header for jenkins authentication
$headers = Get-AuthorizationHeader
$jenkinsfileContent = [IO.File]::ReadAllText($FilePath)
$bodyContent = @{'jenkinsfile'="$jenkinsfileContent"}
$result = Invoke-WebRequest -Method Post -Headers $headers -Uri "$jenkinsUrl/pipeline-model-converter/validate" -Body $bodyContent
Write-Host "-------"
Write-Host "Result: $result"
Write-Host "-------"

If everything is OK you will get a response similiar to:

-------
Result: Jenkinsfile successfully validated.
-------

Otherwise you might get an errorMessage like below if you forgot an }:

-------
Result: Errors encountered validating Jenkinsfile:
WorkflowScript: 192: expecting '}', found '' @ line 192, column 2.
   }
-------