When I have created scripts, that are to used in Production, I put in code that will write events to a specific Event Log so, in the event of a failure, I can use my events as a starting point for resolving the issue.
Writing your own events is relatively easy. As an example, let's say I have a process that should be running 24x7. The first thing to do is to look for the process:
$process = get-process MyProcess -ErrorAction SilentlyContinue
The '-ErrorAction SilentlyContinue' is needed because the get-process code would fail if the process isn't running.
The next step is to make the appropriate event log available to add events:
New-EventLog -LogName Application -Source "My Process Code"
The 'Log-Name' parameter needs to have the correct event log. In this example, we want to add the events to the Application log
The '-Source' parameter is used to give name/label to the event.
At this point, we have the following code for the script:
$process = get-process MyProcess -ErrorAction SilentlyContinue
New-EventLog - LogName Application -Source "My Process Code"
Now that we have information about the process, and have the event log ready, we need to evaluate the $process variable. First, let's check to see if the $process was running:
if($process) {
Write-EventLog -LogName Application -Source "My Process Code" -EntryType information -EventID 3000 -Message "My Process is running"
}
This line of code states that IF $process is true (because there is information in the variable), then write a event into the Application log, the source is My Process Code, the entry type is Information, give the event ID as 3000, and the message is the process is running.
Now, what if $process is empty, meaning the process was not running? We add and Else statement to handle this situation:
Else {
Write-EventLog -LogName Application -Source "My Process Code" -EntryType Error -EventID 3001 Message "My Process is not running"
}
As you can see, only change we made were the entry type, the event ID, and the message.
In my scripts, I will add a line, in the Else code, that restarts the process. So, it would look like this:
Else {
Write-EventLog -LogName Application -Source "My Process Code" -EntryType Error -EventID 3001 Message "My Process is not running"
Invoke-expression "C:\Applications\MyProcess.exe"
}
Here is what the complete script will look like:
$process = get-process MyProcess -ErrorAction SilentlyContinue
New-EventLog - LogName Application -Source "My Process Code"
if($process) {
Write-EventLog -LogName Application -Source "My Process Code" -EntryType information -EventID 3000 -Message "My Process is running"
}
Else {
Write-EventLog -LogName Application -Source "My Process Code" -EntryType Error -EventID 3001 Message "My Process is not running"
Invoke-expression "C:\Applications\MyProcess.exe"
}
I hope you find this article helpful. Please feel free to contact me if you have any questions.
Mike
No comments:
Post a Comment