Guidelines for managing output from remote script block


I just watched the Don Jones tool making video on YouTube where the technique of accumulating output in an array and emitting at the end was specifically not recommended. I had just completed a script where I did that very thing! I am looking for recommendations how to better handle the output in my script.

This gist has the fragment of my script in question. The main script body sets up a script block and calls it with Invoke-Command as a different user. This was done because the account running the script does not have permission to copy the files but the account in $credential does.

Script Fragment

The script uses an exit code to tell the calling Jenkins server whether this job succeeded or not so the script block outputs an exit code as well.

Is there anything particularly problematic about accumulating the output messages in the array in this case?



Well, you’re just outputting text, it looks like. If that’s what the receiving application needs, than you’re probably fine. You have to take my comments in context; I was speaking about a more common scenario where one PowerShell command (like a function) is outputting to another PowerShell command. Accumulating in that scenario blocks the pipeline and is less efficient. But I also pointed out specific cases - like a data sort - where you’ve no choice but to block the pipeline.

In your case it doesn’t look like you’re outputting objects to the pipeline, right? And it looks like you may specifically want your script to block execution until it finishes?

If it works for you it’s not really wrong.

Personally I would only use arrays for like objects, not for logging. Build your pscustomobject with a status column, execute your routine, update the status column with the results then output.

Yes. The caller in this case is a Jenkins job that captures the results text and prints it to it’s own console and log. Jenkins jobs that call a PowerShell or Batch script also pass or fail based on the exit code number.

I liked the idea of separating the tool scripts from the controller scripts. That concept will make it much easier to know to put things.