Majestic Pixel
Majestic Pixel

Reputation: 35

Powershell - Write to Windows Event Viewer

I have small backup script that I use to schedule backups on my Windows Server 2012 machine but I would like to write a small note to the Windows Event Viewer so that I get some form of notification once a backup occurs.

I know that I should make use of the Write-EventLog parameter but I keep messing up the flags that Windows Event Viewer seems to require. I would highly appreciate an example containing the necessary flags, and the values that they should contain so that I may see a simple event.

I'm not sure if it matters, but here is my Powershell script.

$backup = New-WBPolicy
Set-WBPolicy $backup

$date = Get-Date
$date_check = $date.AddDays(-7)
$day = $date.DayOfWeek
$month = $date.Month
$year = $date.Year
$check_year = $date_check.Year
$check_month = $date_check.Month
$check_day = $date_check.DayOfWeek

$date_target = "\\DC01\Backup\$year\$month\$day"
$move_date_target= "\\DC01\Backup\$year\$month"
$check_date_target = "\\DC01\Backup\$check_year\$check_month\$check_day"

$target = New-WBBackupTarget -NetworkPath $date_target
$file_spec = New-WBFileSpec -FileSpec "C:\Windows\SYSVOL"
Add-WBBackupTarget -Policy $backup -Target $target
Add-WBFileSpec -Policy $backup -FileSpec $file_spec
$check_folder = Get-Item $check_date_target


if(-not (Test-Path "\\DC01\Backup\$year"))
{
    New-Item -ItemType directory -Path "\\DC01\Backup\$year"
}

if(-not (Test-Path "\\DC01\Backup\$year\$month"))
{
    New-Item -ItemType directory -Path "\\DC01\Backup\$year\$month"
}

if($date_target -match "[S|s]unday")
{
    if(Test-Path "$date_target\WindowsImageBackup")
    {
        Move-Item "$date_target\WindowsImageBackup" "$move_date_target\WindowsImageBackup-$year-$month-$day"
    }
}


if(-not (Test-Path "\\DC01\Backup\$year\$month\$day"))
{
    New-Item -ItemType directory -Path "\\DC01\Backup\$year\$month\$day"
}

Start-WBBackup $backup

Upvotes: 0

Views: 298

Answers (1)

Peter Schneider
Peter Schneider

Reputation: 2929

You can get online help for each powershell command. So in your case

get-help write-eventlog -online

There you should find an example like this:

write-eventlog -computername Server01 -logname Application 
    -source MyApp -eventID 3001 
    -message "MyApp added a user-requested feature to the display."

You might need the EventSource, if it is missing you can create one (needed only once):

$source ="MyApp"
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
}

Upvotes: 2

Related Questions