Search code examples
powershelljenkinsgroovy

Issue while assigning temp data to hash table in Powershell inside Groovy Script


I am creating a groovy Jenkins pipeline while running PowerShell code inside groovy script. Below is the code I am trying to run inside Groovy.

                    powershell("""

                    \$global:alldistqueue = @()
                    
                    foreach(\$distqueue in \$DISTRIBUTOR_QUEUES)
                    {
                            \$distrow = "" | Select Distributor,QueueName
                            \$distrow.Distributor = "$DISTRIBUTOR_NAME"
                            \$distrow.QueueName = \$distqueue
                            
                            \$global:alldistqueue += \$distrow
                        
                        
                        Write-host "Data \$distrow"

                    }
                        Write-host "\$global:alldistqueue "  """)

Issue is I do not get the data in $global:alldistqueue variable in PowerShell but i checked data is there in $distrow temp variable. Any Idea , Please help on this.

Thanks


Solution

  • When you expand an array or collection variable in a string expression, PowerShell does a simple String.Join operation using the current value of $OFS (the "output-field separator") as a separator.

    This means that if the default string implementation (the ToString() method) for the underlying object type produces empty strings, then your string expression (like "$global:alldistqueues") ends up being all whitespace.

    Instead, use the Out-String cmdlet to force PowerShell to format and render the object as one big string output using its own formatting subsystem - thus bypassing the default ToString() output, before passing it to Write-Host:

    Write-Host $($alldistqueue |Out-String)
    

    Or, escaped for your Groovy source code:

    Write-Host \$(\$alldistqueue |Out-String)