How do I get std-out from Invoke-Command?


I’m using Invoke-Command to execute some script blocks on remote server, how do I get back stdout of my commands back to remote console? For example code below shall error out that module name is not correct but it’s not returning anything

PS C:\Users\gs\desktop> $restart = “import-module Webadministratio”
PS C:\Users\gs\desktop> Invoke-Command server -cred $cred {$restart} -Verbose

Well, you don’t per se. PowerShell doesn’t actually do stdout. Primary output goes to the main pipeline; errors and whatnot are written to other pipelines. Invoke-Command will normally return all of those things to you. So, since you’re getting nothing, that means the remote computer is doing nothing.

Some of what you’re missing is how the command is passed. Try this:

Invoke-Command -server -cred $cred { import-module webadministration } -verbose

And see if it’s any different. Right now, your $restart variable is being passed as a literal to the remote computer; it’s up to the remote computer to decide what $restart contains. Because, on the remote machine, $restart contains nothing, there are no commands actually being run. What you probably want is:

$restart = { import-module webadministration }
invoke-command -computername server -scriptblock $restart -verbose -cred $cred

Bit different.

That’s because you’ve made the command a string
Try this
£> $restart = “import-module Webadministratio”
£> $restart
import-module Webadministratio

All that happens is that the string is echoed back to you.

You need to make the command a script block

£> $restart = {import-module Webadministratio}
£> Invoke-Command -ComputerName $env:COMPUTERNAME -ScriptBlock $restart
The specified module ‘Webadministratio’ was not loaded because no valid module file was found in any module directory.
+ CategoryInfo : ResourceUnavailable: (Webadministratio:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
+ PSComputerName : RSLAPTOP01

and then you get the error you’d expect