Information is Power
Earlier this year, I published an article on creating better PowerShell output. One of the techniques I demonstrated involved using the Write-Information
cmdlet. This cmdlet is underappreciated and, I think, underutilized. I think part of this stems from the fact that the cmdlet isn’t very well understood. There’s also not an easy way to determine when you can use it. I thought I would spend some time today diving into this cmdlet and the [InformationRecord]
object and demonstrate how you can leverage it in your scripting projects.
Let’s begin with a function that uses Write-Information
. I’ll trust that you will read the full cmdlet help and examples.
Function Get-RunningService {
[cmdletbinding()]
Param()
# I'm hiding errors for services I don't have permission
# to get for the sake of a cleaner demonstration
$r = Get-Service -OutVariable all -ErrorAction SilentlyContinue | Where-Object { $_.status -eq 'running' }
Write-Information -MessageData "Found $($r.count) running services out of $($all.count) services"
$r
}
If you run this command, Get-RunningService
, you should get all running services. You shouldn’t see the information message. To get that message, you need to enable the information stream.