This is how I handle logging in my scripts.
I've written a function write-log that I send strings to. The first time the function is used it initializes the file with information in my $FileHeader variable. After that it just appends strings to the file.
Below is the function, the info I use to initialize my file and and example of how I use the function throughout my script.
Also I really hate PowerShell's concatinate operator (+ is just so messy) and find double-quotes much more useful. i.e.
This:
$WriteLog = "" + $Server + " " + $Service + " has been archived"
Looks much better like this:
$WriteLog = "$Server $Service has been archived"
See Dr. Tobias Weltner's Mastering PowerShell page 360 (free e-book
here)
function write-log([string]$info){
if($loginitialized -eq $false){
$FileHeader > $logfile
$script:loginitialized = $True
}
$info >> $logfile
}
<#---------Logfile Info----------#>
$script:logfile = ".\Filename-$(get-date -format MMddyyHHmmss).log"
$script:Seperator = @"
$("-" * 25)
"@
$script:loginitialized = $false
$script:FileHeader = @"
$seperator
***Application Information***
Filename: FileName.ps1
Created by: Cameron
Last Modified: $(Get-Date -Date (get-item .\FileName.ps1).LastWriteTime -f MM/dd/yyyy)
"@
<#----An Example of how to use the Write-Log function----#>
#Delete Accounts
try{
if($Admin -ne "passthru"){
Remove-ADUser $ADUser -Credential $Admin -Server $script:server -Confirm:$false
write-log "`tDeleted user: $($ADUser.distinguishedName)"
} else {
Remove-ADUser $ADUser -Server $script:server -Confirm:$false
write-log "`tDeleted user: $($ADUser.distinguishedName)"
}
} catch {
write-log "Problem deleting ADObject"
write-log $ADUser
write-log $error[0].Exception.GetType().FullName
write-log $error[0].CategoryInfo
}