Below is some powershell to write to the event log; if the -Force
parameter is specified this saves you the effort of writing additional code to first check whether the log exists.
I had to make use of Remove-Variable
to allow some parameters to flow through; I'd not used that feature before / been aware of that nuance, so not sure whether this is the best approach?
cls
$myLog = 'Application'
$mySource = 'My PS Script'
$myEventId = 1
[System.Diagnostics.EventLogEntryType]$myEntryType = [System.Diagnostics.EventLogEntryType]::Error
$myMessage = 'This is a test message'
$myMessage2 = 'This is a test message (2)'
$myMessage3 = 'This is a test message (3)'
function Write-EventLog2
{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]$LogName
,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]$Source
,
[Parameter(Position=3,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Int32]$EventId
,
[Parameter(Position=4,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[System.Diagnostics.EventLogEntryType]$EntryType
,
[Parameter(Position=5,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]$Message
,
[Parameter(Position=6,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[Int16]$Category
,
[Parameter(Position=7,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[String]$ComputerName
,
[Parameter(Position=8,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[Byte[]]$RawData
,
[Parameter(Position=9,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[switch]$Force
)
begin
{
if($Force.IsPresent)
{
if (! ([System.Diagnostics.EventLog]::Exists($LogName) -and [System.Diagnostics.EventLog]::SourceExists($Source) ))
{
New-EventLog -LogName $LogName -Source $Source
}
}
}
process
{
if(!$EntryType) {Remove-Variable EntryType};
if(!$Message) {Remove-Variable Message};
if(!$Category) {Remove-Variable Category};
if(!$ComputerName) {Remove-Variable ComputerName};
if(!$RawData) {Remove-Variable RawData};
Write-EventLog -LogName $LogName -Source $Source -EventId $EventId -EntryType $EntryType -Message $Message #-Category $Category -ComputerName $ComputerName -RawData $RawData
}
#end{} #no ending actions required
}
Write-EventLog2 $myLog $mySource $myEventId $myEntryType $myMessage -Force #ensure the log's created if doesn't exist
Write-EventLog2 $myLog $mySource $myEventId $myEntryType $myMessage2 -Force #just to demo that we don't get an error if source already exists
Write-EventLog2 $myLog $mySource $myEventId $myEntryType $myMessage3 #this is how we'd generall call once we were certain the command had been called at least once with -Force
Show-EventLog #check that the above code produced the expected logs