First published on TECHNET on Mar 01, 2012
So continuing along with file manipulation I created a function that will write to our log file as well as the Application event log so that we could record everything we want and if necessary elevate the importance of a message by recording it in the event log.
So first thing is what parameters does it collect:
ScriptSource - This is used as the source when we write to the Application event log
LoggingChoice - Do you want to log to the file, the event log, or both
Message - What do you want to write to your log
Type - Is it an error, warning, or Information
EventNumber - a number you create to for the application event log
LogFile - Path and name of log you want to write to
Now let's go thru a bit of the logic
So first off I create an Event log using New-EventLog then I do a little bit of checking on the variables to insure that things like the Type are spelled correctly (Very important when you write the event log), or that the log file is actually where you say it is.
Then based on LoggingChoice we take the appropriate action of either A) Writing to just the log file B) Writing to just the Application event log or C) Writing to both.
switch ($LoggingChoice)
{
0
{
Write-EventLog -LogName Application -Source $ScriptSource -EventID $EventNumber -EntryType $Type -Message $Message
break
}
1
{
Add-Content -Path $LogFile -Value "[$Date][$Type][$EventNumber]$Message"
break
}
2
{
Write-EventLog -LogName Application -Source $ScriptSource -EventID $EventNumber -EntryType $Type -Message $Message
Add-Content -Path $LogFile -Value "[$Date][$Type][$EventNumber]$Message"
break
}
default
{
Write-EventLog -LogName Application -Source $ScriptSource -EventID $EventNumber -EntryType $Type -Message $Message
break
}
}
If you would like to check out the function you can download it from here