Search code examples
powershellscriptblock

command execution ordering inside a PowerShell scriptblock


I got excited with PowerShell ScriptBlock at first but I was confused recently with its executing ordering inside blocks. For example:

$test_block = {
  write-host "show 1"
  ps
  write-host "show 2"
  Get-Date
}

The output by calling $test_block.Invoke():

show 1
show 2
<result of command 'ps'>
<result of command 'get-date'>

Do commands who output something run first?


Solution

  • This behaviour is because write-host doesn't put the output on the pipeline. The other commands are placed on the pipeline so are not output to the screen until the function (invoke) returns.

    To get the behaviour I believe you were expecting, use write-output instead, the results of all the commands will then be returned in the pipeline.

    $test_block = {
      write-output "show 1"
      ps
      write-output "show 2"
      Get-Date
    }
    
    $test_block.Invoke()