Tuesday, August 23, 2016

Getting verbose output from an Invoke-Command -ScriptBlock in PowerShell

It's often very useful to invoke commands on other machines, e.g. in deployment scripts. It can be even more useful to have logging of what actually gets executed on those other machines, e.g.

$myJob = Invoke-Command -AsJob -ScriptBlock {
    Param()

    Do-Thing -Verbose
}

However, in this instance, you wouldn't get the output of the Do-Thing command because it's writing to the Verbose stream of a script block being executed on a separate machine. Now, it's not that PowerShell can't collect the output of that Verbose stream for you, it can. You just need to instruct it how. The difference:

$myJob = Invoke-Command -AsJob -Verbose -ScriptBlock {
    [CmdletBinding()]
    Param()

    Do-Thing -Verbose
}

Now you'll be able to collect the Verbose output of your script block. The difference is that you need to pass the Verbose flag to the script block, and make it a cmdlet by adding the [CmdletBinding()] attribute to your block.

No comments: