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}
$command.Invoke()
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 [email protected]','[email protected]','subjectText',($command.Invoke()) )
Thanks
{ScriptBlock}.Invoke()
returns aSystem.Collections.ObjectModel.Collection<PSObject>
which is getting mangled by theWrite-Host
command.If you use
InvokeReturnAsIs()
you get correct results:Format-List
return formatting objects. You needOut-String
cmdlet to convert them to string:Then you can pass that string into methods, which expect string as their input.