Multiple commands within ScriptBlock

Alexander Edwards picture Alexander Edwards · Aug 1, 2016 · Viewed 22.5k times · Source

I'm having trouble running multiple commands within a Scriptblock parameter. All documentation points towards using a semicolon for separation between cmdlets. Using the same methodology of separating cmdlets via a semicolon works on my local machine, but not on a remote machine through invoke-command.

For example, the below code will only return the result of Get-Service, and not Get-Process.

Invoke-Command -ComputerName cas-bkupexec -ScriptBlock { Get-Service;  Get-Process }

How can I achieve the desired result of both commands successfully running and receive the output of each?

Answer

briantist picture briantist · Aug 1, 2016

I am able to reproduce this.. it only returns the first statement. It's not the semicolon, it does the same thing if you use like breaks.

These options work:

Invoke-Command -ComputerName computer -ScriptBlock {
    (Get-Service)
    Get-Process
}

Or this curiously:

Invoke-Command -ComputerName computer -ScriptBlock {
    & { 
        Get-Service
        Get-Process
    }
}

Since wrapping one of them in ( ) works I feel like this must be some quirk of the pipeline but I haven't been able to figure out exactly what it's doing yet.

Update:

After reading your comment that your source machine was running v5 and the remote v2, I realized that my testing did the same.

When I remoted from the v5 into itself, the issue disappeared.

Remoting from:

v2 -> v5: no issue
v2 -> itself: no issue
v2 -> other v2: no issue
v3 -> v2: no issue
v3 -> v5: no issue
v3 -> itself: no issue
v4 -> v2: no issue
v4 -> v3: no issue
v4 -> itself: no issue
v4 -> v5: no issue

Not every combination here, but it seems like it really may be a bug from v5 to v2.