Logging mid pipe in Powershell

I've been writing a lot of powershell recently and I really like the functional aspect of piping:

$Websites |
    Stop-Website -Passthru |
    Remove-Website

As it's a lot easier to read than constantly using foreach to iterate through collections. The Stop-Website cmdlet will stop the website and pass on an object that the Remove-Website cmdlet will accept.

The problem with this pattern is it doesn't leave much room for logging, or so I thought. EdDebug was kind to point out that if the result of the last line in a statement will be returned and passed on. So you can use the current object shorthand combined with Write-Host to do some logging:

$Website |
    % { Write-Host "Stopping icenet website $($_.Name)"; $_ } |
    Stop-Website -Passthru |
    % { Write-Host "Removing icenet website $($_.Name)"; $_ } |
    Remove-Website

I think that still looks pretty tidy.

Comments