My logging method has two parts, a script block and an invoke-command line. Its not the typical function call. Just a small piece to get started, and lay the support for recording what your script is going to do.
First we create a path for the log with date stamp
$logLocation = "c:\beep\logs\$($MyInvocation.MyCommand.Name)_$(get-date -f "MM_dd").log"
The scriptblock has 2 parameters $msg and $quiet. Msg is the text you want to record in the log and Quiet is a switch that allows console output to be silenced. The block will loop until its able to change the updated variable, affectively retrying until the write completes or the counter reaches 5. Each line is date stamped. If not quiet then write the message to the console.
$logMsg = {
param([string]$msg,[switch]$quiet)
$updated = $false
$cnt = 0
while(!$updated -or $cnt -ge 5)
{ try
{ "$(get-date -f "MM/dd/yyyy HH:mm:ss") - $($msg)" | Out-File $logLocation -Append}
catch{$cnt ++}
$updated = $true
}
if(!$quiet){$msg}
}
#Call log routine
Invoke-Command $logMsg -ArgumentList "Starting script: $($MyInvocation.MyCommand.Name)"
No comments:
Post a Comment