Tuesday, October 10, 2006

Windows PowerShell and WMI

I started working with PowerShell with the RC2 after spending some time with IronPython.

Most of what I know now goes to the credit of http://mow001.blogspot.com/

My first real problem was to get security events out of the Windows EventLog using WMI.
Unlike regular WMI queries the Security EventLog requires the caller to have the SeSecurityPrivilege activated.

In VBScript this can be expressed on connecting to the namespace:

Set objWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate,(Security)}!\\" & strComputer & "\root\cimv2")

Since get-wmiobject has (at least in RC2) no parameter for either privileges or the ImpersonationLevel I found two ways around this problem:

You can manually use .NET classes from the Management Namespace .

$scope = [Management.ManagementScope]"root\cimv2"
$scope.Options.EnablePrivileges = 1
$query = [Management.ObjectQuery]"SELECT * FROM Win32_NTLogEvent WHERE Logfile='Security'"
$searcher = [Management.ManagementObjectSearcher]""
$searcher.Scope = $scope
$searcher.Query = $query
$events = $searcher.Get()


Later I found out that there is a much more convenient solution using the [WmiSearcher] object:

$searcher = [WmiSearcher]""
$searcher.Scope.Options.EnablePrivileges = 1
$searcher.Query = "SELECT * FROM Win32_NTLogEvent WHERE Logfile='Security'"
$events = $searcher.Get()



Greetings,
G/\/\E

Blog reopened

Today I started blogging again after two years of absense.
Time will tell whether I keep writing or give up after a few days...