Store PS command output to variable and Invoke-Command

Posted on

Store PS command output to variable and Invoke-Command – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about windows, powershell, scripting, , .

I need to store command output to pass it as variable in function later

#This works
[scriptblock]$command = {Get-EventLog system -newest 1  | Format-List}

But when I try to Write-Host it fails

#This works
[scriptblock]$command = {Get-EventLog system -newest 1  | Format-List}
Write-Host $command.Invoke()

with output

Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData

Line of the script in which I’m trying to use it is

$SMTPMessage = New-Object System.Net.Mail.MailMessage('UserName user@my.domain','user2@my.domain','subjectText',($command.Invoke()) )


Solution :

Format-List return formatting objects. You need Out-String cmdlet to convert them to string:

$OutputAsString = $command.Invoke() | Out-String

Then you can pass that string into methods, which expect string as their input.

{ScriptBlock}.Invoke() returns a System.Collections.ObjectModel.Collection<PSObject> which is getting mangled by the Write-Host command.

If you use InvokeReturnAsIs() you get correct results:

PS C:> [scriptblock]$command = {Get-EventLog system -newest 1  | Format-List}

Index              : 141723
EntryType          : Information
InstanceId         : 1073748860
Message            : The Application Experience service entered the stopped state.
Category           : (0)
CategoryNumber     : 0
ReplacementStrings : {Application Experience, stopped}
Source             : Service Control Manager
TimeGenerated      : 9/8/2016 9:32:02 AM
TimeWritten        : 9/8/2016 9:32:02 AM
UserName           : 

Leave a Reply

Your email address will not be published.