Home > OS >  Save powershell return value in a Jenkins Variable
Save powershell return value in a Jenkins Variable

Time:05-04

I have a scripted pipeline in Jenkins and I am calling a powershell script to generate links to files in onedrive so I can mail them using the plug-in in the next step. I have tried using the following to get this done

def return_val = powershell script: "Path\\to\\script\\someScript.ps1", returnStatus: true based on this answer here

However, I get

Caught: groovy.lang.MissingMethodException: No signature of method: hudson7145251072251175654.node() is applicable for argument types: (hudson7145251072251175654$_run_closure1) values: [hudson7145251072251175654$_run_closure1@46271dd6] Possible solutions: use([Ljava.lang.Object;), notify(), wait(), run(), run(), any()

This is the powershell script I am using.

#Config Variables
$SiteURL = "https://company-my.sharepoint.com/personal/name"
$FolderURL= "/Documents/Desktop" #Folder's Site Relative Path
Connect-PnPOnline -Url $SiteURL -Interactive
$Context.Credentials = $Credentials
$linklist =[System.Collections.ArrayList]@()
linkfunction {
    $FolderItems = @(Get-PnPFolderItem -FolderSiteRelativeUrl $FolderURL -ItemType File)
    foreach($item in $folderItems)
      {
        $linklist.Add($item.Name)
        Write-Host $linklist
      }
    return $linklist

CodePudding user response:

powershell returnStatus: true only returns the numeric exit code from the PowerShell script (which is 0 on success but could be set to a different value by calling exit 42 from PowerShell for instance).

To return strings or other complex data from PowerShell to Groovy, you need to use powershell returnStdout: true. This gives you the whole output from PowerShell that is written to the success output stream as a single, possibly multiline string.

A simplified PowerShell script:

$list = [System.Collections.ArrayList]@()
$null = $list.Add('foo\bar')
$null = $list.Add('baz')
$list  # Implicit output, a "return" statement is not required in PowerShell

Assigning to $null makes sure that the return value of ArrayList.Add() doesn't end as (unwanted) output of the PowerShell script.

This outputs each array element on its own line:

foo\bar
baz

To turn the PowerShell output back into an array on the Groovy side we can do:

def return_val = powershell script: "Path\\to\\script\\someScript.ps1", returnStdout: true
def return_array = return_val.split(/\r?\n/)

Here return_val is a single multiline string. Using the String.split() method we turn it back into an array and store it in variable return_array.

String.split() expects a regular expression, that defines where to split the string. The RegEx \r?\n splits on both Windows \r\n and Unix-style \n line ends. I'm using slashy string literal to avoid having to escape the backslashes, very handy for RegEx patterns.

  • Related