August 23, 2013

How to use write-verbose with an object

When you are debugging some times you want to use the write-verbose cmdlet to display an object or a collection.  It would have been really nice to be able to do :

write-verbose (Get-EventLog -LogName system -Newest 3 -EntryType Error)

unfortunately this will produce an error :

Write-Verbose : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Message'. Specified method is not supported.

The write-verbose cmdlet only takes a string as a paramter, objects are not allowed.
The trick is to use the out-string cmdlet like this :

write-verbose (Get-EventLog -LogName system -Newest 3 -EntryType Error | Out-String)

You can event make it look a little bit prettier :

write-verbose (Get-EventLog -LogName system -Newest 5 -EntryType Error| format-list -Property TimeGenerated,Entrytype,EventID,Source,Message | out-string)

No comments:

Post a Comment