Logging for non-PSADT commands

Why use PSADT’s Set-Registry function instead of powershell’s own Set-item cmdlet?
Why use PSADT’s copy-file function instead of powershell’s own copy-item cmdlet?
Answer: Logging, error handling and handling of special cases.

But what about the Non-PSADT functions? You know, the built-in stuff.
Here are 2 methods:

1. Redirection
This the quick and dirty method that I use when I can:

Remove-NetFirewallRule -DisplayName $RuleName -Verbose *>&1 | Out-String | write-log

Use the -Verbose switch to make sure Write-log has something to write. Otherwise Write-log will blow up and take to the whole script with it.
It works most times but some fancy cmdlets still don’t report errors like Set-Service .

2. Cmdlet variables
This is another way to force logging out of cmdlets. it is a bit more work but it’s the only way for some cmdlets:

$OutputText = Set-Service -Name AdobeARMservice -Verbose -StartupType Disabled -ErrorVariable ErrVar -OutVariable OutVar -WarningVariable WarnVar -ErrorAction SilentlyContinue | Out-String
Write-Log "[$OutputText] [$ErrVar] [$OutVar] [$WarnVar]"
Remove-variable OutputText,ErrVar,OutVar,WarnVar -ErrorAction SilentlyContinue

The only thing you will want to watch-out for is the -ErrorAction switch. Yon might need to set it to STOP to make Try/Catch work.

CAVEAT: Not all cmdlets work with both methods.
Expand-Archive is one example. This will work fine:

Expand-Archive -Path "$dirFiles\Stuff.zip" -DestinationPath "$env:ProgramFiles\Stuff" -Force -Verbose *>&1 | Out-String | write-log

Using the cmdlet variables method however, will record [] [] [] [] regardless of success or failure:

$OutputText = Expand-Archive -Path "$dirFiles\Stuff.zip" -DestinationPath "$env:ProgramFiles\Stuff" -Force -Verbose -ErrorVariable ErrVar -OutVariable OutVar -WarningVariable WarnVar -ErrorAction SilentlyContinue | Out-String
Write-Log "[$OutputText] [$ErrVar] [$OutVar] [$WarnVar]"
Remove-Variable OutputText,ErrVar,OutVar,WarnVar -ErrorAction SilentlyContinue

Other logging tips

Get directory listing into the PSADT log file

#DIR is an alias to Get-ChildItem
#Out-string removes characters and object stuff that may make Write-log blow up
#-ErrorAction SilentlyContinue is there in-case the folder does not exist
Write-log "[$(Dir "C:\Program Files\Office" -ErrorAction SilentlyContinue | Out-String)]"