Posts

Showing posts from October, 2016

How To Write to the Event Log in C#

I've been doing a lot of C# developing for Microsoft Exchange lately and I would like to share with you a few lines of C# that I've found to be very useful in event handling. I prefer using the windows event logs and not text files for logging since they will not grow out of control and are very easy to search and handle. The function below will create an event in the specified log, under the specified source with the provided information: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 private static void WriteEvent (String LogName, String EventSource, String EventBody, int EventId, EventLogEntryType EventType) { try { using (EventLog eventLog = new EventLog(LogName)) { if (!EventLog.SourceExists(EventSource)) EventLog.CreateEventSource(EventSource, LogName); eventLog.Source = EventSource; eventLog.W

Powershell: How to pass a parameter to a scriptblock

Scriptblock. Very common in the powershell world and used by many cmdlets and functions like Invoke-Command. But how can we pass a parameter to the scriptblock? Lets say that we are developing a function that will execute a command on remote computers. As a real world example, I want to check the status of a service on remote computers. I need however my function to be agile and accept the name of the service to check. Since I am going to be using the Invoke-Command cmdlet, I need to pass the name of the service to the scriptblock parameter. Fortunatelly, this is fairly easy and cam be accomplished using the param statement in the scriptblock just like: Invoke-Command -ComputerName $Computer ` -ScriptBlock { param ( $ServiceName ) Get-Service -Name $ServiceName } ` -ArgumentList $ServiceName Of course, the Get-Service has a ComputerName parameter for this purpose but this is just an example.