├── Functions ├── Get-ToDoList.ps1 ├── Get-WmiEventBinding.ps1 ├── Get-WmiEventConsumer.ps1 ├── Get-WmiEventFilter.ps1 ├── New-WmiEventConsumer.ps1 ├── New-WmiEventFilter.ps1 ├── New-WmiFilterToConsumerBinding.ps1 ├── Remove-WmiEventBinding.ps1 ├── Remove-WmiEventConsumer.ps1 ├── Remove-WmiEventFilter.ps1 ├── Set-ScriptingStandardConsumerSetting.ps1 ├── Test-Get-WmiEventConsumer.ps1 ├── Test-Get-WmiEventFilter.ps1 └── Test-IsAdministrator.ps1 ├── Install Module.ps1 ├── PowerEvents.psd1 ├── PowerEvents.psm1 ├── README.md ├── Samples ├── Event Binding - Command Line - Microsoft Outlook Started.ps1 ├── Event Binding - Command Line - System Resumed - Restart Windows Service.ps1 ├── Event Binding - Command Line - User Profile Unloaded - Delete Unused Profiles.ps1 ├── Event Binding - Event Log - Process Creation.ps1 ├── Event Binding - Event Log - Process Termination.ps1 ├── Event Binding - Log File - Print Job Completed.ps1 ├── Event Binding - Log File - Print Job Created.ps1 ├── Event Binding - Log File - Process Creation.ps1 ├── Event Binding - Script - Print Job Completed.ps1 ├── Event Binding - Script - Print Job Created.ps1 ├── Event Binding - Script - UFD Installed.ps1 ├── Event Binding - Script - UFD Removed.ps1 ├── Event Binding - ScriptFile - UFD Installed.ps1 ├── Event Binding - ScriptFile - UFD Removed.ps1 ├── Event Binding - Test Command Line VBscript with Process Start Events.ps1 ├── Event Consumers │ ├── Command Line - Microsoft Outlook Started.ps1 │ ├── Command Line - User Profile Loaded.ps1 │ ├── Command Line - User Profile Unloaded - Delete Unloaded Profiles.ps1 │ ├── Command Line - User Profile Unloaded - Run VBscript.ps1 │ ├── CommandLine - PowerShellTest.ps1 │ ├── CommandLine - Script With Args.ps1 │ ├── ConfigMgr │ │ └── ConfigMgr - System Resource Created.ps1 │ ├── Event Log - Process Creation.ps1 │ ├── Event Log - Process Termination.ps1 │ ├── Log File - Print Job Completed.ps1 │ ├── Log File - Print Job Created.ps1 │ ├── Log File - Process Created.ps1 │ ├── Log File - Process Terminated.ps1 │ ├── Script - Print Job Completed.ps1 │ ├── Script - Print Job Created.ps1 │ ├── Script - UFD Installed.ps1 │ ├── Script - UFD Removed.ps1 │ ├── ScriptFile - UFD Installed.ps1 │ ├── ScriptFile - UFD Removed.ps1 │ ├── VBscripts │ │ ├── UFD Installed.vbs │ │ └── User Profile Loaded.vbs │ └── Windows │ │ ├── Command Line - System Resumed - Restart Windows Service.ps1 │ │ └── Support │ │ └── Restart Windows Service.ps1 ├── Event Filters │ ├── Active Directory │ │ ├── Event Filter - Active Directory - Computer Created.ps1 │ │ ├── Event Filter - Active Directory - Computer Deleted.ps1 │ │ ├── Event Filter - Active Directory - User Created.ps1 │ │ └── Event Filter - Active Directory - User Deleted.ps1 │ ├── Clustering │ │ ├── Event Filter - Cluster State Changed.ps1 │ │ ├── Event Filter - Cluster State Offline.ps1 │ │ └── Event Filter - Cluster State Online.ps1 │ ├── ConfigMgr │ │ ├── Event Filter - ConfigMgr - Advertisement Created.ps1 │ │ ├── Event Filter - ConfigMgr - Advertisement Deleted.ps1 │ │ ├── Event Filter - ConfigMgr - Collection Created.ps1 │ │ ├── Event Filter - ConfigMgr - Collection Deleted.ps1 │ │ ├── Event Filter - ConfigMgr - Package Created.ps1 │ │ ├── Event Filter - ConfigMgr - Package Deleted.ps1 │ │ └── Event Filter - ConfigMgr - Resource Created.ps1 │ ├── Event Filter - Microsoft Outlook Started.ps1 │ └── Windows │ │ ├── Event Filter - IP Address Changed.ps1 │ │ ├── Event Filter - Print Job Completed.ps1 │ │ ├── Event Filter - Print Job Created.ps1 │ │ ├── Event Filter - Process Created.ps1 │ │ ├── Event Filter - Process Terminated.ps1 │ │ ├── Event Filter - System Resumed.ps1 │ │ ├── Event Filter - UFD Installed.ps1 │ │ ├── Event Filter - UFD Removed.ps1 │ │ ├── Event Filter - User Profile Loaded.ps1 │ │ └── Event Filter - User Profile Unloaded.ps1 ├── README.txt └── Test-PowerEvents.ps1 └── WmiEventHelper ├── WmiEventHelper.sln └── WmiEventHelper ├── Form1.Designer.cs ├── Form1.cs ├── Form1.resx ├── Program.cs ├── Properties ├── AssemblyInfo.cs ├── Resources.Designer.cs ├── Resources.resx ├── Settings.Designer.cs └── Settings.settings ├── WmiEventHelper.csproj ├── WmiEventHelper.idc ├── app.config └── bin └── Debug ├── WmiEventHelper.exe.config ├── WmiEventHelper.vshost.exe.config └── WmiEventHelper.vshost.exe.manifest /Functions/Get-ToDoList.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | Author: Trevor Sullivan 4 | Date: 2014-02-09 5 | Purpose: Retrieves a list of TODO items from the supporting scripts of this 6 | PowerShell module, and indicates the line number and file in which each 7 | item is located. 8 | #> 9 | 10 | Clear-Host; 11 | $ScriptList = Get-ChildItem -Path $PSScriptRoot\* -Include *.ps1; 12 | 13 | foreach ($Script in $ScriptList) { 14 | $Result = (Get-Content -Path $Script.FullName) -match '(?<=#.*)(? 23 | Param( 24 | # The name of the WMI event filter to retrieve. The name property is the key on the __FilterToConsumerBinding system WMI class. 25 | [Parameter( 26 | Mandatory = $false 27 | , HelpMessage = "Please specify the name of the WMI event filter instance that you would like to retrieve bindings for." 28 | , ParameterSetName = 'filter' 29 | )] 30 | [string] 31 | ${Filter} 32 | , 33 | [Parameter(ParameterSetName = 'consumer')] 34 | [string] 35 | ${Consumer} 36 | , 37 | # The WMI namespace to retrieve event filters from. 38 | # TODO: Provide an option to retrieve ALL event filters from ALL namespaces? 39 | [Parameter(ValueFromPipelineByPropertyName = $true)] 40 | [Alias('ns')] 41 | [string] 42 | ${Namespace} 43 | , 44 | [Parameter(ValueFromPipelineByPropertyName = $true)] 45 | [Alias('cn')] 46 | [ValidateScript({ 47 | if (Test-Connection -ComputerName $_ -Count 1) { $true; } 48 | else { $false; } 49 | })] 50 | [string] 51 | ${ComputerName} = '.' 52 | , 53 | # TODO: Implement parameter to allow searching of the query text 54 | [string] 55 | ${QuerySearchString} 56 | , 57 | [Parameter(ParameterSetName = 'all')] 58 | [switch] 59 | ${All} 60 | ) 61 | 62 | begin 63 | { 64 | # Get the cmdlet name for writing dynamic log messages 65 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name 66 | ${ParameterSetName} = $Pscmdlet.ParameterSetName; 67 | 68 | Write-Verbose -Message "${CmdletName}: Start running BEGIN block"; 69 | } 70 | 71 | process { 72 | Write-Verbose -Message "${CmdletName}: Start running PROCESS block"; 73 | 74 | if (${ParameterSetName} = 'all') { 75 | $BindingList = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${Namespace} -Class __FilterToConsumerBinding; 76 | } 77 | elseif (${ParameterSetName} = 'filter') { 78 | ${WmiQuery} = "REFERENCES OF {__EventFilter='{0}'} WHERE ResultClass = __FilterToConsumerBinding" -f ${Filter}; 79 | $BindingList = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${Namespace} -Query ${WmiQuery} -ErrorAction Stop; 80 | } 81 | elseif (${ParameterSetName} = 'consumer') { 82 | ${WmiQuery} = "REFERENCES OF {__EventConsumer='{0}'} WHERE ResultClass = __FilterToConsumerBinding" -f ${Consumer}; 83 | $BindingList = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${Namespace} -Query ${WmiQuery} -ErrorAction Stop; 84 | } 85 | # Get a list of WMI filter-to-consumer bindings 86 | 87 | if ($BindingList) { 88 | Write-Output -InputObject $BindingList; 89 | } 90 | else { 91 | Write-Error -Message ('{0}: Could not find any matching WMI event bindings' -f ${CmdletName}); 92 | } 93 | # Translate asterisks (wildcards) to percent signs (WMI wildcards) 94 | #${Name} = ${Name}.Replace("*", "%"); 95 | } 96 | 97 | end { 98 | } 99 | } 100 | 101 | # Export the Get-WmiEventBinding function 102 | Export-ModuleMember -Function Get-WmiEventBinding; 103 | 104 | # Export an alias for the function 105 | New-Alias -Name gwmib -Value Get-WmiEventBinding; 106 | Export-ModuleMember -Alias gwmib -------------------------------------------------------------------------------- /Functions/Get-WmiEventConsumer.ps1: -------------------------------------------------------------------------------- 1 | function Get-WmiEventConsumer 2 | { 3 | <# 4 | .Synopsis 5 | Retrieves WMI event consumer objects. 6 | 7 | .Description 8 | Retrieves WMI event consumers instances based on criteria passed to the function. The -Namespace All parameter value can be used to retrieve instances in all WMI namespaces on a given computer. 9 | 10 | .Link 11 | http://trevorsullivan.net 12 | 13 | .Link 14 | http://powershell.artofshell.com 15 | #> 16 | 17 | [CmdletBinding( 18 | SupportsShouldProcess = $false 19 | , SupportsTransactions = $false 20 | , ConfirmImpact = 'Low' 21 | )] 22 | 23 | #region PARAM block 24 | param ( 25 | [parameter( 26 | Mandatory = $false 27 | , HelpMessage = "Please specify the name of event consumer you would like to retrieve." 28 | )] 29 | [string] 30 | ${Name} 31 | , 32 | [Parameter(ValueFromPipelineByPropertyName = $true)] 33 | [string] 34 | ${Namespace} = 'root\subscription' 35 | , 36 | # In the interest of think + type, I've adjusted these types from their actual WMI class names 37 | # EventLog = NTEventLogEventConsumer 38 | # LogFile = LogFileEventConsumer 39 | # Script = ActiveScriptEventConsumer 40 | # CommandLine = CommandLineEventConsumer 41 | # SMTP = SMTPEventConsumer 42 | [parameter( 43 | Mandatory = $false 44 | , HelpMessage = "Please specify the type of event consumer you would like to retrieve." 45 | )] 46 | [ValidateSet( 47 | 'EventLog' 48 | , 'LogFile' 49 | , 'CommandLine' 50 | , 'Script' 51 | , 'SMTP' 52 | )] 53 | [alias('Type')] 54 | ${ConsumerType} 55 | , 56 | [Parameter(ValueFromPipelineByPropertyName = $true)] 57 | [Alias('cn')] 58 | [ValidateScript({ 59 | if (Test-Connection -ComputerName $_ -Count 1) { $true; } 60 | else { $false; } 61 | })] 62 | [string] 63 | ${ComputerName} = '.' 64 | ) 65 | #endregion PARAM block 66 | 67 | Begin 68 | { 69 | # Get the cmdlet name for writing dynamic log messages 70 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name; 71 | Write-Verbose -Message ('{0}: Start running BEGIN block' -f ${CmdletName}); 72 | 73 | $ConsumerClasses = @{ 74 | Script = "ActiveScriptEventConsumer"; 75 | SMTP = "SMTPEventConsumer"; 76 | EventLog = "NTEventLogEventConsumer"; 77 | LogFile = "LogFileEventConsumer"; 78 | CommandLine = "CommandLineEventConsumer"; 79 | } 80 | } 81 | 82 | Process 83 | { 84 | Write-Verbose -Message ('{0}: Start running BEGIN block' -f ${CmdletName}); 85 | 86 | if (${Namespace} -ne 'All') 87 | { 88 | # Translate asterisks (wildcards) to percent signs (WMI wildcards) 89 | ${Name} = ${Name}.Replace("*", "%") 90 | 91 | # $ConsumerList is an array that holds a list of WMI event consumers returned from WMI. 92 | # If multiple namespaces are queries for consumers, this will consolidate the results into a single variable. 93 | $ConsumerList = @(); 94 | 95 | ${ConsumerQuery} = "select * from __EventConsumer"; 96 | if ($ConsumerType) { 97 | ${ConsumerQuery} += " where __CLASS = '{0}'" -f ${ConsumerClasses}.${ConsumerType}; 98 | } 99 | 100 | Write-Verbose -Message ("${CmdletName}: Consumer query is: " + ${ConsumerQuery}); 101 | ${EventConsumerList} = Get-WmiObject -ComputerName ${ComputerName} -Query ${ConsumerQuery} -Namespace ${Namespace}; 102 | 103 | if (${EventConsumerList}) 104 | { 105 | Write-Verbose -Message ("${CmdletName}: Retrieved " + $Filters.Count + " event consumers from the ${Namespace} namespace."); 106 | foreach ($EventConsumer in $EventConsumerList) { 107 | ${ConsumerList} += ${EventConsumer}; 108 | } 109 | } 110 | else 111 | { 112 | Write-Verbose -Message ("${CmdletName}: Could not find any consumers with the specified name and type."); 113 | } 114 | 115 | 116 | Write-Output -InputObject ${ConsumerList}; 117 | } 118 | else 119 | { 120 | 121 | } 122 | } 123 | 124 | end { 125 | Write-Verbose -Message ('{0}: Start running END block' -f ${CmdletName}); 126 | } 127 | } 128 | 129 | # Export the Get-WmiEventConsumer function 130 | Export-ModuleMember -Function Get-WmiEventConsumer 131 | 132 | # Create an alias for the function 133 | New-Alias -Name gwmic -Value Get-WmiEventConsumer; 134 | Export-ModuleMember -Alias gwmic; -------------------------------------------------------------------------------- /Functions/Get-WmiEventFilter.ps1: -------------------------------------------------------------------------------- 1 | function Get-WmiEventFilter 2 | { 3 | [CmdletBinding(SupportsShouldProcess = $false)] 4 | <# 5 | .Synopsis 6 | Retrieves an existing WMI event filter. 7 | 8 | .Description 9 | Retrieves an existing WMI event filter. 10 | 11 | .Parameter Namespace 12 | The namespace in which to retrieve __EventFilter instances from. 13 | 14 | .Parameter Name 15 | The name of the __EventFilter instance to retrieve. 16 | 17 | .Parameter ComputerName 18 | The computer on which to retrieve __EventFilter instances. 19 | 20 | .Parameter QuerySearchString 21 | String to search for inside the event filter's query text. 22 | 23 | .Inputs 24 | 25 | #> 26 | Param( 27 | # The name of the WMI event filter to retrieve. The name property is the key on the __EventFilter system WMI class. 28 | [Parameter( 29 | Mandatory = $false 30 | , HelpMessage = "Please specify the name of the __EventFilter instance you would like to retrieve. Wildcards are acceptable." 31 | , ValueFromPipelineByPropertyName = $true 32 | , ValueFromPipeline = $true 33 | )] 34 | [string] 35 | ${Name} 36 | , 37 | # The WMI namespace to retrieve event filters from. 38 | # TODO: Provide an option to retrieve ALL event filters from ALL namespaces? 39 | [Parameter(ValueFromPipelineByPropertyName = $true)] 40 | [string] 41 | ${Namespace} = 'root\subscription' 42 | , 43 | [Parameter(ValueFromPipelineByPropertyName = $true)] 44 | [ValidateScript({ 45 | if (Test-Connection -ComputerName $_ -Count 1) { $true; } 46 | else { $false; } 47 | })] 48 | [string] 49 | ${ComputerName} = '.' 50 | , 51 | # TODO: Implement parameter to allow searching of the query text 52 | [string] 53 | [ValidateNotNull()] 54 | ${QuerySearchString} 55 | ) 56 | 57 | begin 58 | { 59 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name; 60 | 61 | Write-Debug -Message "${CmdletName}: `${Name} parameter's value is: ${Name}"; 62 | Write-Debug -Message "${CmdletName}: `${Namespace} parameter's value is: ${Name}"; 63 | Write-Debug -Message "${CmdletName}: `${QuerySearchString} parameter's value is: ${Name}"; 64 | 65 | if (${Name}) 66 | { 67 | # Translate asterisks (wildcards) to percent signs (WMI wildcards) 68 | ${Name} = ${Name}.Replace("*", "%"); 69 | ${EventFilters} = Get-WmiObject -Namespace ${Namespace} -Query "SELECT * FROM __EventFilter WHERE Name LIKE '${Name}'"; 70 | } 71 | else 72 | { 73 | # Translate asterisks (wildcards) to percent signs (WMI wildcards) 74 | ${QuerySearchString} = ${QuerySearchString}.Replace("*", "%"); 75 | ${EventFilters} = Get-WmiObject -Query "SELECT * FROM __EventFilter WHERE Query LIKE '${QuerySearchString}'"; 76 | } 77 | 78 | if (${EventFilters}) 79 | { 80 | Write-Verbose -Message "${CmdletName}: Found $(${EventFilters}.psbase.Length) event filters"; 81 | Write-Output -InputObject ${EventFilters}; 82 | } 83 | else 84 | { 85 | Write-Warning -Message "${CmdletName}: No event filters were found with the specified criteria."; 86 | } 87 | } 88 | } 89 | 90 | Export-ModuleMember -Function Get-WmiEventFilter; 91 | 92 | # Create alias for the Get-WmiEventFilter function 93 | New-Alias -Name gwmif -Value Get-WmiEventFilter; 94 | Export-ModuleMember -Alias gwmif; -------------------------------------------------------------------------------- /Functions/New-WmiEventConsumer.ps1: -------------------------------------------------------------------------------- 1 |  2 | # TODO: Test creation of WMI Event Consumer on remote machine (should work fine) 3 | # TODO: Finish comment-based help (add several .Example) 4 | # TODO: Check for existence of script file during consumer creation 5 | # TODO: Consolidate certain parameters (eg. Message, Text, InsertionStringTemplate) that do more or less the same thing 6 | 7 | #region New-WmiEventConsumer 8 | function New-WmiEventConsumer 9 | { 10 | 11 | <# 12 | .Synopsis 13 | Creates a new, permanent WMI event consumer. 14 | 15 | .Description 16 | Creates a permanent WMI event consumer, leveraging the out-of-box classes provided by Microsoft. The consumer class, and related configuration, can be specified as parameters. 17 | 18 | .Parameter Name 19 | The name for the the event consumer. Giving a consumer a name is not required, however it is strongly recommended, to make referencing it in the future easier. 20 | 21 | .Parameter ComputerName 22 | The computer name to create the WMI event consumer on. Requires administrative access to the remote computer. 23 | 24 | .Parameter ConsumerType 25 | The type of event consumer you would like to use. This can be any of the following values: EventLog, LogFile, CommandLine, Script, or SMTP. These values represent the five out-of-box event consumers available in the Windows operating system. 26 | 27 | .Parameter Timeout 28 | The execution timeout for CommandLineEventConsumer and ActiveScriptEventConsumer instances. 29 | 30 | .Parameter Namespace 31 | The WMI namespace that you would like to create the new event consumer in. Typically in practice, this will be root\subscription, as that is where the out-of-box event consumer classes reside. 32 | 33 | .Parameter ScriptFile 34 | The path to the script file you would like to execute, if using the ActiveScriptEventConsumer (VBscript consumer) class. 35 | 36 | .Parameter ScriptingEngine 37 | The scripting engine to use for execution of the script in the ActiveScriptEventConsumer. In practice, this will almost always be "VBscript." 38 | 39 | .Parameter ScriptText 40 | ScriptText is used if ScriptFile is not available. Script code can be embedded inside the event consumer. Most often, this will simply be VBscript code. 41 | 42 | .Parameter CommandLineTemplate 43 | Ideally used instead of ExecutablePath. The standard string template that specifies the process to be started for the CommandLineEventConsumer. 44 | 45 | .Parameter ExecutablePath 46 | Module to execute. The string can specify the full path and file name of the module to execute, or it can specify a partial name. If a partial name is specified, the current drive and current directory are assumed. 47 | 48 | .Parameter WorkingDirectory 49 | The working directory for the CommandLineEventConsumer instance. 50 | 51 | .Parameter BccLine 52 | The BCC property for a SMTPEventConsumer instance. Either a [string[]] or a comma or semicolon delimited list of e-mail addresses. 53 | 54 | .Parameter CcLine 55 | The CC property for a SMTPEventConsumer instance. Either a [string[]] or a comma or semicolon delimited list of e-mail addresses. 56 | 57 | .Parameter FromLine 58 | From line of an email message in the format of a standard string template. If NULL, a From line is constructed in the form of WinMgmt@MachineName. 59 | 60 | .Parameter Message 61 | Standard string template that contains the body of an email message. 62 | 63 | .Parameter ReplyToLine 64 | Reply-to line of an email message in the format of a standard string template. If NULL, no Reply-to line is used. 65 | 66 | .Parameter Subject 67 | Standard string template that contains the subject of an email message. 68 | 69 | .Parameter ToLine 70 | A list of addresses, separated by a comma or semicolon, in the format of a standard string template that identifies where the message is to be sent. 71 | 72 | .Parameter FileName 73 | Name of a file that includes the path to which the log entries are appended. If the file does not exist, LogFileEventConsumer attempts to create it. The consumer fails when the path does not exist, or when the user who creates the consumer does not have write permissions for the file or path. 74 | 75 | .Parameter IsUnicode 76 | If TRUE, the log file is a Unicode text file. If FALSE, the log file is a multibyte code text file. If the file exists, this property is ignored and the current file setting is used. For example, if IsUnicode is FALSE, but the existing file is a Unicode file, then Unicode is used. If IsUnicode is TRUE, but the file is multibyte code, then multibyte code is used. 77 | 78 | .Parameter MaximumFileSize 79 | Maximum size of a log file—in bytes. If the primary file exceeds its maximum size, the contents are moved to a different file and the primary file is emptied. A value of 0 (zero) means there is no size limit. The default value is 65,535 bytes. The size of the file is checked before a write operation. Therefore, you can have a file that is slightly larger than the specified size limit. The next write operation catches it and starts a new file. 80 | 81 | .Parameter Text 82 | Standard string template for the text of a log entry. Details available at: http://msdn.microsoft.com/en-us/library/aa393954(v=VS.85).aspx 83 | 84 | .Parameter Category 85 | A UInt16 value representing the event log category. Must not be null. 86 | 87 | .Parameter EventId 88 | Event message in the message DLL. This property cannot be NULL. 89 | 90 | .Parameter EventType 91 | The event type to use for the NTEventLogEventConsumer. Valid values are: 'Success', 'Error', 'Warning', 'Information', 'AuditSuccess', 'AuditFailure' 92 | 93 | .Parameter InsertionStringTemplates 94 | An array of string templates that the provider will use to insert event log entries. This parameter uses WMI standard string templates. 95 | 96 | .Parameter UncServerName 97 | The name of the computer on which you would like to log the event to. 98 | 99 | .Link 100 | http://trevorsullivan.net 101 | 102 | .Link 103 | http://powershell.artofshell.com 104 | 105 | .Link 106 | http://msdn.microsoft.com/en-us/library/aa392395(v=VS.85).aspx 107 | 108 | .Link 109 | http://msdn.microsoft.com/en-us/library/aa394647(v=VS.85).aspx 110 | 111 | .Link 112 | http://msdn.microsoft.com/en-us/library/aa393954(v=VS.85).aspx 113 | 114 | .Link 115 | http://www.streamline-it-solutions.co.uk/blog/post/Configuring-WMI-Event-Handling-with-PowerShell.aspx 116 | 117 | .Link 118 | http://www.codeproject.com/KB/system/PermEvtSubscriptionMOF.aspx?display=Print#5.TemporaryEventConsumers4 119 | #> 120 | 121 | [CmdletBinding( 122 | SupportsShouldProcess = $false 123 | , SupportsTransactions = $false 124 | , ConfirmImpact = 'Low' 125 | )] 126 | #region New-WmiEventConsumer Parameters 127 | Param( 128 | #region New-WmiEventConsumer General Parameters 129 | # In the interest of think + type, I've adjusted these types from their actual WMI class names 130 | # EventLog = NTEventLogEventConsumer 131 | # LogFile = LogFileEventConsumer 132 | # Script = ActiveScriptEventConsumer 133 | # CommandLine = CommandLineEventConsumer 134 | # SMTP = SMTPEventConsumer 135 | [parameter( 136 | Mandatory = $true 137 | , HelpMessage = "Please specify the type of event consumer you would like to create." 138 | )] 139 | [ValidateSet( 140 | "EventLog" 141 | , "LogFile" 142 | , "CommandLine" 143 | , "Script" 144 | , "SMTP" 145 | )] 146 | [alias("Type")] 147 | ${ConsumerType} 148 | , 149 | [parameter( 150 | Mandatory = $false 151 | , HelpMessage = "Please specify the WMI namespace to create the event consumer in." 152 | )] 153 | [alias("ns", "WmiNamespace")] 154 | [string] 155 | ${Namespace} = 'root\default' 156 | , 157 | [parameter( 158 | Mandatory = $false 159 | , HelpMessage = "Please specify a name for this WMI event consumer." 160 | )] 161 | [string] 162 | ${Name} = $null 163 | , 164 | # TODO: Investigate if 10 is an adequate default number for this parameter (it's NOT) 165 | [parameter( 166 | Mandatory = $false 167 | , HelpMessage = "Please specify the maximum queue size (in bytes) for this event consumer." 168 | )] 169 | [Int32] 170 | ${MaximumQueueSize} = $null 171 | , 172 | [parameter( 173 | Mandatory = $false 174 | , HelpMessage = "Please specify the computer to create the consumer on." 175 | )] 176 | [ValidateScript({ 177 | if (Test-Connection -ComputerName $_ -Count 1) { $true; } 178 | else { $false; } 179 | })] 180 | [Alias('pc', 'cn')] 181 | [string] 182 | ${ComputerName} = 'localhost' 183 | , 184 | [parameter( 185 | Mandatory = $false 186 | , ParameterSetName = "Script" 187 | , HelpMessage = "Please enter the timeout (in seconds) for the ActiveScriptEventConsumer." 188 | )] 189 | [parameter( 190 | Mandatory = $false 191 | , ParameterSetName = "CommandLine" 192 | , HelpMessage = "Please enter the timeout (in seconds) for the CommandLineEventConsumer." 193 | )] 194 | [Int32] 195 | ${Timeout} = 60 196 | #endregion New-WmiEventConsumer General Parameters 197 | #region ParameterSet: ActiveScriptEventConsumer 198 | # MSDN Documentation for ActiveScriptEventConsumer: http://msdn.microsoft.com/en-us/library/aa384749(VS.85).aspx 199 | , 200 | [parameter( 201 | Mandatory = $false 202 | , ParameterSetName = "Script" 203 | , HelpMessage = 'Please enter the path to the VBscript file that will handle events.' 204 | )] 205 | [string] 206 | ${ScriptFile} = $null 207 | , 208 | [parameter( 209 | Mandatory = $false 210 | , ParameterSetName = "Script" 211 | , HelpMessage = 'Please enter the script engine to use for the ActiveScriptEventConsumer (eg. VBscript).' 212 | )] 213 | [string] 214 | [alias("Engine")] 215 | ${ScriptingEngine} = 'VBScript' 216 | , 217 | # TODO: ScriptText should be a DynamicParam, in the event that $ScriptFile is not defined 218 | [parameter( 219 | Mandatory = $false 220 | , ParameterSetName = "Script" 221 | , HelpMessage = "Please specify the script code to be executed for this consumer." 222 | )] 223 | [string] 224 | # TODO: Make sure that ${ScriptFile} over-writes ${ScriptText} parameter 225 | [ValidateScript( { 226 | Write-Debug ([Runspace]::DefaultRunspace).InstanceId 227 | Write-Debug "`${ScriptFile} value is: ${ScriptFile}" 228 | if (${ScriptFile} -eq $null) 229 | { 230 | $_ -ne $null 231 | } 232 | } )] 233 | ${ScriptText} = $null 234 | #endregion ParameterSet: ActiveScriptEventConsumer 235 | #region ParameterSet: CommandLineEventConsumer 236 | # TODO: Add more parameters to the CommandLineEventConsumer (maybe, if deemed necessary) 237 | , 238 | # According to MSDN (http://msdn.microsoft.com/en-us/library/aa389231(v=VS.85).aspx) either the CommandLineTemplate can be used 239 | # or if it is null, then the ExecutablePath property can be used instead. 240 | [parameter( 241 | Mandatory = $false 242 | , ParameterSetName = "CommandLine" 243 | , HelpMessage = "Please specify the command line for the CommandLineEventConsumer." 244 | )] 245 | ${CommandLineTemplate} = $null 246 | , 247 | [parameter( 248 | Mandatory = $false 249 | , ParameterSetName = "CommandLine" 250 | , HelpMessage = "Please specify the executable for the CommandLineEventConsumer." 251 | )] 252 | [string] 253 | ${ExecutablePath} = $null 254 | , 255 | [parameter( 256 | Mandatory = $false 257 | , ParameterSetName = "CommandLine" 258 | , HelpMessage = "Please specify a working directory." 259 | )] 260 | [string] 261 | ${WorkingDirectory} = $null 262 | <# 263 | # PARAMETER IS NOT USED 264 | # See MSDN: http://msdn.microsoft.com/en-us/library/aa389231(v=VS.85).aspx 265 | , 266 | [parameter( 267 | Mandatory = $false 268 | , ParameterSetName = "CommandLine" 269 | , HelpMessage = "Please specify whether or not a new console should be opened." 270 | )] 271 | [bool] 272 | ${CreateNewConsole} = $true 273 | #> 274 | , 275 | [parameter( 276 | Mandatory = $false 277 | , ParameterSetName = "CommandLine" 278 | , HelpMessage = "Please specify whether or not the command should be run interactively." 279 | )] 280 | [bool] 281 | ${RunInteractively} = $false 282 | #endregion ParameterSet: CommandLineEventConsumer 283 | #region ParameterSet: SMTPEventConsumer 284 | # MSDN SMTPEventConsumer: http://msdn.microsoft.com/en-us/library/aa393629(v=VS.85).aspx 285 | , 286 | [parameter( 287 | Mandatory = $false 288 | , ParameterSetName = "SMTP" 289 | , HelpMessage = "Please enter a list of e-mail addresses to blind carbon-copy (BCC) as a [String[]], or a [String] containing a comma or semicolon delimited list." 290 | )] 291 | [String[]] 292 | ${BccLine} = $null 293 | , 294 | [parameter( 295 | Mandatory = $false 296 | , ParameterSetName = "SMTP" 297 | , HelpMessage = "Please enter a list of e-mail addresses to carbon copy (CC) as a [String[]], or a [String] containing a comma or semicolon delimited list." 298 | )] 299 | [String[]] 300 | ${CcLine} = $null 301 | , 302 | [parameter( 303 | Mandatory = $false 304 | , ParameterSetName = "SMTP" 305 | , HelpMessage = "Please enter the text you would like to appear in the 'From' line of notification e-mails." 306 | )] 307 | [String] 308 | ${FromLine} = $null 309 | <# 310 | # UNSUPPORTED PARAMETER -- not sure how to use it yet 311 | , 312 | [parameter( 313 | Mandatory = $false 314 | , ParameterSetName = "SMTP" 315 | , HelpMessage = "CURRENTLY UNSUPPORTED! Please enter the additional header fields you'd like to add to the e-mail." 316 | )] 317 | [String] 318 | ${HeaderFields} = $null 319 | #> 320 | , 321 | [parameter( 322 | Mandatory = $true 323 | , ParameterSetName = "SMTP" 324 | , HelpMessage = "Please enter the text you would like to appear in the body of the e-mail message." 325 | )] 326 | [String] 327 | ${Message} = $null 328 | , 329 | [parameter( 330 | Mandatory = $false 331 | , ParameterSetName = "SMTP" 332 | , HelpMessage = "Please enter the text you would like to appear in the Reply-to area of the e-mail message." 333 | )] 334 | [String] 335 | ${ReplyToLine} = $null 336 | , 337 | [parameter( 338 | Mandatory = $true 339 | , ParameterSetName = "SMTP" 340 | , HelpMessage = "Please the IP address or DNS name of the SMTP server." 341 | )] 342 | [String] 343 | ${SMTPServer} = $null 344 | , 345 | [parameter( 346 | Mandatory = $false 347 | , ParameterSetName = "SMTP" 348 | , HelpMessage = "Please enter the text you would like to appear in the Subject field of the e-mail message." 349 | )] 350 | [String] 351 | ${Subject} = $null 352 | , 353 | [parameter( 354 | Mandatory = $false 355 | , ParameterSetName = "SMTP" 356 | , HelpMessage = "Please enter the e-mail address of the receipient." 357 | )] 358 | [String] 359 | [alias("Recipient")] 360 | ${ToLine} = $null 361 | #endregion ParameterSet: SMTPEventConsumer 362 | #region ParameterSet: LogFileEventConsumer 363 | # (DONE) TODO: Add parameters for LogFileEventConsumer 364 | # (MSDN) LogFileEventConsumer: http://msdn.microsoft.com/en-us/library/aa392277(v=VS.85).aspx 365 | , 366 | [parameter( 367 | Mandatory = $true 368 | , ParameterSetName = "LogFile" 369 | , HelpMessage = 'Please specify the full path of the log file to log to.' 370 | )] 371 | [string] 372 | # TODO: Add file name validation to this parameter 373 | # TODO: Add validation of user permissions to log file path 374 | # [ValidateScript({ $_.IndexOfAny })] 375 | ${FileName} 376 | , 377 | [parameter( 378 | Mandatory = $false 379 | , ParameterSetName = "LogFile" 380 | , HelpMessage = 'Please specify whether or not the file is unicode. Valid values: $true or $false' 381 | )] 382 | [bool] 383 | ${IsUnicode} = $true 384 | , 385 | [parameter( 386 | Mandatory = $false 387 | , ParameterSetName = "LogFile" 388 | , HelpMessage = 'Please specify a maximum file size for the log file. Default is 65,535.' 389 | )] 390 | [int] 391 | ${MaximumFileSize} = 65535 392 | , 393 | [parameter( 394 | Mandatory = $false 395 | , ParameterSetName = "LogFile" 396 | , HelpMessage = 'Please specify the text template for the consumer. See http://msdn.microsoft.com/en-us/library/aa393954(v=VS.85).aspx for template information.' 397 | )] 398 | # TODO: Add validation for template syntax? Maybe. http://msdn.microsoft.com/en-us/library/aa393954(v=VS.85).aspx 399 | [string] 400 | ${Text} 401 | #endregion ParameterSet: LogFileEventConsumer 402 | #region ParameterSet: NTEventLogEventConsumer 403 | # (DONE) TODO: Add parameters for NTEventLogEventConsumer 404 | # (MSDN) NTEventLogEventConsumer: http://msdn.microsoft.com/en-us/library/aa392715(v=VS.85).aspx 405 | , 406 | [parameter( 407 | Mandatory = $false 408 | , ParameterSetName = "EventLog" 409 | , HelpMessage = 'Please specify the event category for this event log consumer.' 410 | )] 411 | [ValidateNotNull()] 412 | [UInt16] 413 | ${Category} = 10 414 | , 415 | [parameter( 416 | Mandatory = $true 417 | , ParameterSetName = "EventLog" 418 | , HelpMessage = 'Please specify the event ID for this event log consumer.' 419 | )] 420 | [ValidateNotNull()] 421 | [UInt32] 422 | ${EventId} 423 | , 424 | [parameter( 425 | Mandatory = $true 426 | , ParameterSetName = "EventLog" 427 | , HelpMessage = 'Please specify the event type for this event log consumer.' 428 | )] 429 | # These are normalized values that will translate into numeric values from winnt.h 430 | # http://source.winehq.org/source/include/winnt.h 431 | [ValidateSet( 432 | "Success" # EVENTLOG_SUCCESS = 0x0000 433 | , "Error" # EVENTLOG_ERROR_TYPE = 0x0001 434 | , "Warning" # EVENTLOG_WARNING = 0x0002 435 | , "Information" # EVENTLOG_INFORMATION_TYPE = 0x0004 436 | , "AuditSuccess" # EVENTLOG_AUDIT_SUCCESS = 0x0008 437 | , "AuditFailure" # EVENTLOG_AUDIT_FAILURE = 0x0010 438 | )] 439 | ${EventType} 440 | , 441 | # TODO: Rename this parameter to -EventMessage? 442 | [parameter( 443 | Mandatory = $true 444 | , ParameterSetName = "EventLog" 445 | , HelpMessage = 'Please specify the array of string templates for this event log consumer.' 446 | )] 447 | [String[]] 448 | [Alias("MessageTemplates")] 449 | ${InsertionStringTemplates} 450 | , 451 | # TODO: Test the use of a NTEventLogEventConsumer to log an event on a remote server or workstation. 452 | [parameter( 453 | Mandatory = $false 454 | , ParameterSetName = "EventLog" 455 | , HelpMessage = 'Please specify the computer you would like to log the event on.' 456 | )] 457 | [string] 458 | # TODO: Use script validation to ensure remote computer is available? 459 | # TODO: Use -Force parameter to force creation of event consumer against remote event log even if remote computer is unavailable? Maybe. 460 | ${UNCServerName} 461 | , 462 | [parameter( 463 | Mandatory = $false 464 | , ParameterSetName = "EventLog" 465 | , HelpMessage = 'Please specify the source name for the event. If none is specified, the parameter will default to "UnknownEventSource"' 466 | )] 467 | [string] 468 | ${SourceName} = 'UnknownEventSource' 469 | #endregion ParameterSet: NTEventLogEventConsumer 470 | ) 471 | #endregion New-WmiEventConsumer Parameters 472 | 473 | #region New-WmiEventConsumer Begin block 474 | begin 475 | { 476 | # Get the cmdlet name for writing dynamic log messages 477 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name 478 | 479 | Write-Debug -Message "${CmdletName}: Runspace ID is: $(([Runspace]::DefaultRunspace).InstanceId)"; 480 | 481 | Write-Verbose -Message "${CmdletName}: Start running BEGIN block"; 482 | Write-Verbose -Message ("${CmdletName}: Using the parameter set: " + $Pscmdlet.ParameterSetName); 483 | # TODO: Convert BccLine and CcLine from [string[]] to comma or semicolon separated lists of e-mail addresses 484 | # TODO: Validate that both ${ScriptText} and ${ScriptFilename} are not BOTH $null (AND ${ConsumerType} is Script) 485 | 486 | # This is a lookup hashtable, so that the parameter can take the friendly names, and they can later be translated into their numeric values 487 | # Used for NTEventLogEventConsumer.EventType property 488 | $EventTypes = @{ 489 | Success = 0; 490 | Error = 1; 491 | Warning = 2; 492 | Information = 4; 493 | AuditSuccess = 8; 494 | AuditFailure = 16; 495 | } 496 | 497 | <# 498 | #region DEPRECATED CODE 499 | # (DONE) TODO: IMPORTANT: Translate $EventType into numeric values from winnt.h - See: http://source.winehq.org/source/include/winnt.h 500 | # (DONE) TODO: Convert this to a hashtable for easier reference 501 | if ($Pscmdlet.ParameterSetName -eq 'EventLog') 502 | { 503 | Write-Verbose -Message "Event type is: ${EventType}" 504 | switch (${EventType}) 505 | { 506 | 'Success' 507 | { 508 | ${EventType} = [int]0 509 | } 510 | 'Error' 511 | { 512 | ${EventType} = [int]1 513 | } 514 | 'Warning' 515 | { 516 | ${EventType} = [int]2 517 | } 518 | 'Information' 519 | { 520 | ${EventType} = [int]4 521 | } 522 | 'AuditSuccess' 523 | { 524 | ${EventType} = [int]8 525 | } 526 | 'AuditFailure' 527 | { 528 | ${EventType} = [int]16 529 | } 530 | $null 531 | { 532 | Write-Verbose '${EventType} is $null, assuming unused' 533 | } 534 | # Unrecognized value passed to ${EventType}. This should be caught in the argument validation, but if not, this ought to take care of it 535 | default 536 | { 537 | Write-Error -Category InvalidArgument -Message 'Invalid value specified for ${EventType} argument.' -RecommendedAction 'Use one of the following values for EventType: Success, Warning, Error, Information, AuditSuccess, AuditFailure' 538 | } 539 | } 540 | } 541 | #endregion END DEPRECATED CODE 542 | #> 543 | } 544 | #endregion New-WmiEventConsumer Begin block 545 | 546 | #region New-WmiEventConsumer process block 547 | process 548 | { 549 | switch (${ConsumerType}) 550 | { 551 | #region ActiveScriptEventConsumer 552 | # If the consumer type is a script, then we will create an instance of ActiveScriptEventConsumer 553 | # Documentation: http://msdn.microsoft.com/en-us/library/aa384749(VS.85).aspx 554 | 'Script' 555 | { 556 | # Create a new instance of the ActiveScriptEventConsumer class 557 | ${NewConsumer} = ([wmiclass]"\\${ComputerName}\root\subscription:ActiveScriptEventConsumer").CreateInstance() 558 | # Set the KillTimeout property of ActiveScriptEventConsumer 559 | # (MSDN): Number, in seconds, that the script is allowed to run. If 0 (zero), which is the default, the script is not terminated. 560 | # ${NewConsumer}.{KillTimeout} = ${Timeout} 561 | # Set the MachineName property on ActiveScriptEventConsumer 562 | # (MSDN): Name of the computer to which WMI sends events. By convention of Microsoft standard consumers, the script consumer cannot be run remotely. Third-party consumers can also use this property. This property is inherited from __EventConsumer. 563 | # ${NewConsumer}.{MachineName} = ${ComputerName} 564 | 565 | # If the ${ScriptFile} parameter is specified, then set the ScriptFile property on ActiveScriptEventConsumer 566 | # IMPORTANT: Even if ${ScriptFile} is $null, DO NOT define the WMI property, otherwise WMI will think the value is defined 567 | if (${ScriptFile}) 568 | { 569 | ${NewConsumer}.{ScriptFilename} = ${ScriptFile} 570 | Write-Verbose -Message "${CmdletName}: Defined the ScriptFilename property" 571 | } 572 | else 573 | { 574 | Write-Verbose -Message "${CmdletName}: `${ScriptFile} parameter is null; using ScriptText instead" 575 | } 576 | 577 | # The ScriptingEngine on ActiveScriptEventConsumer should always be set to "VBscript" 578 | # I am not aware of any other supported values at this point -- the only other option I could think of might be "jscript" 579 | # (MSDN): Name of the scripting engine to use, for example, "VBScript". This property cannot be NULL. 580 | ${NewConsumer}.{ScriptingEngine} = ${ScriptingEngine} 581 | Write-Verbose -Message "${CmdletName}: Defined the ScriptingEngine property" 582 | 583 | # Define the MaximumQueueSize property on ActiveScriptEventConsumer 584 | # (MSDN): Maximum queue, in bytes, for the Active Script Event consumer. This property is inherited from __EventConsumer. 585 | if (${MaximumQueueSize}) 586 | { 587 | ${NewConsumer}.{MaximumQueueSize} = ${MaximumQueueSize} 588 | Write-Verbose -Message "${CmdletName}: Defined the MaximumQueueSize property" 589 | } 590 | else 591 | { 592 | Write-Verbose -Message "${CmdletName}: `${MaximumQueueSize} is null. Skipping ..." 593 | } 594 | 595 | 596 | # ONLY set the ActiveScriptEventConsumer.ScriptText property if it is defined. 597 | # TODO: Make sure that ${ScriptFile} and ${ScriptText} parameters do not conflict with each other 598 | if (${ScriptText} -and -not ${ScriptFile}) 599 | { 600 | ${NewConsumer}.{ScriptText} = ${ScriptText} 601 | Write-Verbose -Message "${CmdletName}: Defined the ScriptText property" 602 | } 603 | # Warn user if ${ScriptText} is empty. If it is defined, but empty, the event consumer will yield no action. 604 | #elseif (${ScriptText} -eq '') { Write-Warning '${ScriptText} was defined, but is empty. No action will occur for this event consumer.' } 605 | else 606 | { 607 | Write-Verbose "${CmdletName}: `${ScriptText} parameter is null OR ScriptFile property has already been specified on `${NewConsumer}." 608 | } 609 | 610 | # Set the friendly name of the new ActiveScriptEventConsumer. 611 | # Note: The Name property is the key for the ActiveScriptEventConsumer class 612 | ${NewConsumer}.{Name} = ${Name} 613 | ${PutResult} = ${NewConsumer}.Put() 614 | Write-Verbose -Message "${CmdletName}: Completed instantiating new ActiveScriptEventConsumer: $(${PutResult}.{Path})" 615 | 616 | # Retrieve and write new WMI instance to pipeline 617 | Write-Output -InputObject $([wmi]"$(${PutResult}.{Path})") 618 | } 619 | #endregion ActiveScriptEventConsumer 620 | 621 | #region CommandLineEventConsumer 622 | # If the consumer type is a command line, then we will create an instance of CommandLineEventConsumer 623 | # (MSDN): http://msdn.microsoft.com/en-us/library/aa389231(v=VS.85).aspx 624 | 'CommandLine' 625 | { 626 | # Create a new instance of CommandLineEventConsumer 627 | ${NewConsumer} = ([wmiclass]"\\${ComputerName}\root\subscription:CommandLineEventConsumer").CreateInstance() 628 | 629 | # If ${CommandLineTemplate} parameter is defined, use it. 630 | # (MSDN): Standard string template that specifies the process to be started. This property can be NULL, and the ExecutablePath property is used as the command line. 631 | if (${CommandLineTemplate}) 632 | { 633 | ${NewConsumer}.{CommandLineTemplate} = ${CommandLineTemplate} 634 | Write-Verbose -Message "${CmdletName}: Defined the CommandLineTemplate property: ${CommandLineTemplate}" 635 | } 636 | else 637 | { 638 | Write-Verbose -Message "${CmdletName}: `${CommandLineTemplate} parameter is not defined. Using ${ExecutablePath} parameter instead." 639 | } 640 | 641 | 642 | # Define MaximumQueueSize property 643 | if (${MaximumQueueSize}) 644 | { 645 | ${NewConsumer}.{MaximumQueueSize} = ${MaximumQueueSize} 646 | Write-Verbose "${CmdletName}: Setting MaximumQueueSize to: ${MaximumQueueSize}" 647 | } 648 | else 649 | { 650 | Write-Verbose -Message "${CmdletName}: MaximumQueueSize was not specified" 651 | } 652 | 653 | # Define WorkingDirectory 654 | if (${WorkingDirectory}) 655 | { 656 | ${NewConsumer}.{WorkingDirectory} = ${WorkingDirectory} 657 | Write-Verbose -Message "${CmdletName}: Set WorkingDirectory property to ${WorkingDirectory}" 658 | } 659 | else 660 | { 661 | Write-Verbose -Message "${CmdletName}: WorkingDirectory parameter was not set." 662 | } 663 | 664 | # If ${Name} parameter is defined, then set it, otherwise provider will automatically assign a GUID as the name 665 | # (MSDN): Unique name of a consumer. 666 | if (${Name}) 667 | { 668 | ${NewConsumer}.{Name} = ${Name} 669 | Write-Verbose -Message "${CmdletName}: `${Name} parameter defined on consumer: ${Name}" 670 | } 671 | else 672 | { 673 | Write-Verbose -Message "${CmdletName}: `${Name} parameter not defined. Using random GUID for name." 674 | Write-Warning -Message "${CmdletName}: `${Name} parameter not specified. It is highly recommended to use name" 675 | } 676 | 677 | if (${ExecutablePath}) 678 | { 679 | ${NewConsumer}.{ExecutablePath} = ${ExecutablePath} 680 | Write-Verbose -Message "${CmdletName}: ExecutablePath property set to: ${ExecutablePath}" 681 | } 682 | else 683 | { 684 | Write-Verbose -Message "${CmdletName}: `${ExecutablePath} is not defined. Using `${CommandLineTemplate} instead." 685 | } 686 | 687 | # Write the WMI instance to the provider 688 | ${PutResult} = ${NewConsumer}.Put(); 689 | Write-Verbose -Message "Completed instantiating new CommandLineEventConsumer: $(${PutResult}.{Path})" 690 | Write-Output -InputObject $([wmi]"$(${PutResult}.{Path})"); 691 | } 692 | #endregion CommandLineEventConsumer 693 | 694 | #region SMTPEventConsumer 695 | # If the consumer type is SMTP, then we will create an instance of SMTPEventConsumer 696 | # (MSDN): http://msdn.microsoft.com/en-us/library/aa393629(VS.85).aspx 697 | 'SMTP' 698 | { 699 | # Create new instance of SMTPEventConsumer 700 | ${NewConsumer} = ([wmiclass]"root\subscription:SMTPEventConsumer").CreateInstance() 701 | 702 | # If ${Name} parameter is defined, then set it, otherwise provider will automatically assign a GUID as the name 703 | # (MSDN): Unique name of a consumer. 704 | if (${Name}) 705 | { 706 | ${NewConsumer}.{Name} = ${Name} 707 | Write-Verbose -Message "${CmdletName}: Defined the Name property" 708 | } 709 | else 710 | { 711 | Write-Verbose -Message '${Name} parameter not defined. Using random GUID for name.' 712 | } 713 | 714 | # Define the BccLine property on SMTPEventConsumer 715 | # (MSDN): A list of addresses, separated by a comma or semicolon, in the format of a standard string template to which the message is sent as a blind carbon copy. 716 | if (${BccLine}) { 717 | ${NewConsumer}.{BccLine} = ${BccLine} 718 | Write-Verbose -Message "${CmdletName}: Defined the BccLine property" 719 | } 720 | else 721 | { 722 | Write-Verbose -Message "${CmdletName}: `${BccLine} is $null, skipping property" 723 | } 724 | 725 | # Define the CcLine property on SMTPEventConsumer 726 | # (MSDN): A list of addresses, separated by a comma or semicolon, in the format of a standard string template to which the message is sent as a carbon copy. 727 | if (${CcLine}) { 728 | ${NewConsumer}.{CcLine} = ${CcLine} 729 | Write-Verbose -Message "${CmdletName}: Defined the CcLine property" 730 | } 731 | else 732 | { 733 | Write-Verbose -Message "${CmdletName}: `${CcLine} parameter is $null, skipping property" 734 | } 735 | 736 | # Define the FromLine property on SMTPEventConsumer 737 | # (MSDN): From line of an email message in the format of a standard string template. If NULL, a From line is constructed in the form of WinMgmt@MachineName. 738 | # (MSDN): Windows Server 2003: If NULL, FromLine is constructed as "WMI@MachineName". If not NULL, then what is specified in the FromLine property is used, and the consumer sets "WMI@MachineName" as the Sender in the SMTP header of the message. This sender cannot be controlled by any property of the SMTPEventConsumer. 739 | # (MSDN): Windows XP: If NULL, FromLine is constructed as "WinMgmt@MachineName via WMI auto-mailer". 740 | if (${FromLine}) { 741 | ${NewConsumer}.{FromLine} = ${FromLine} 742 | Write-Verbose -Message "${CmdletName}: Defined the FromLine property" 743 | } 744 | else 745 | { 746 | Write-Verbose -Message "${CmdletName}: `${FromLine} is $null, skipping property" 747 | } 748 | 749 | # Define the Message property on SMTPEventConsumer 750 | # (MSDN): Standard string template that contains the body of an email message. 751 | if (${Message}) { 752 | ${NewConsumer}.{Message} = ${Message} 753 | Write-Verbose -Message 'Defined the Message property' 754 | } 755 | else { Write-Verbose -Message '${Message} is $null, skipping property' } 756 | 757 | # Define the ReplyToLine property on SMTPEventConsumer 758 | # (MSDN): Reply-to line of an email message in the format of a standard string template. If NULL, no Reply-to line is used. 759 | if (${ReplyToLine}) { 760 | ${NewConsumer}.{ReplyToLine} = ${ReplyToLine} 761 | Write-Verbose -Message 'Defined the ${ReplyToLine} property' 762 | } 763 | else { Write-Verbose '${ReplyToLine} is $null, skipping property' } 764 | 765 | # Define the SMTPServer property on SMTPEventConsumer 766 | # (MSDN): Name of the SMTP server through which an email is sent. Permissible names are an IP address, or a DNS or NetBIOS name. This property cannot be NULL. 767 | if (${SMTPServer}) { 768 | ${NewConsumer}.{SMTPServer} = ${SMTPServer} 769 | Write-Verbose -Message 'Defined the SMTPServer property' 770 | } 771 | else { Write-Verbose '${SMTPServer} is $null, skipping property' } 772 | 773 | # Define the Subject property on SMTPEventConsumer 774 | # (MSDN): Standard string template that contains the subject of an email message. 775 | if (${Subject}) { 776 | ${NewConsumer}.{Subject} = ${Subject} 777 | Write-Verbose -Message 'Defined the ${Subject} property' 778 | } 779 | else { Write-Verbose -Message '${Subject} is $null, skipping property' } 780 | 781 | # Define the ToLine property on SMTPEventConsumer 782 | # (MSDN): Standard string template that contains the subject of an email message. 783 | if (${ToLine}) { 784 | ${NewConsumer}.{ToLine} = ${ToLine} 785 | Write-Verbose -Message 'Defined the ToLine property' 786 | } 787 | else { Write-Verbose -Message '${ToLine} is $null, skipping property' } 788 | 789 | # Write new instance of SMTPEventConsumer back to WMI provider 790 | ${PutResult} = ${NewConsumer}.Put() 791 | Write-Verbose -Message 'Completed creation of SMTPEventConsumer.' 792 | 793 | Write-Output -InputObject ([wmi]"$(${PutResult}.{Path})") 794 | } 795 | #endregion SMTPEventConsumer 796 | 797 | #region LogFileEventConsumer 798 | # (DONE) TODO: Add support for LogFileEventConsumer 799 | # If the consumer type is a command line, then we will create an instance of LogFileEventConsumer 800 | # Documentation: http://msdn.microsoft.com/en-us/library/aa392277(VS.85).aspx 801 | 'LogFile' 802 | { 803 | ${NewConsumer} = ([wmiclass]"\\${ComputerName}\root\subscription:LogFileEventConsumer").CreateInstance() 804 | Write-Verbose -Message "${CmdletName}: Created new instance of LogFileEventConsumer"; 805 | 806 | if (${Name}) 807 | { 808 | ${NewConsumer}.{Name} = ${Name} 809 | Write-Verbose -Message "${CmdletName}: Defined the Name property of LogFileEventConsumer instance."; 810 | } 811 | else 812 | { 813 | Write-Warning "${CmdletName}: `${Name} parameter not specified. Using random GUID as consumer's name."; 814 | } 815 | 816 | # Documentation: Name of a file that includes the path to which the log entries are appended. If the file does not exist, LogFileEventConsumer attempts to create it. The consumer fails when the path does not exist, or when the user who creates the consumer does not have write permissions for the file or path. 817 | if (${FileName}) 818 | { 819 | ${NewConsumer}.{FileName} = ${FileName} 820 | Write-Verbose -Message "${CmdletName}: Defined the FileName property of the LogFileEventConsumer instance." 821 | } 822 | # If ${FileName} is $null, then we have a problem 823 | else 824 | { 825 | Write-Error -Message '${FileName} parameter is $null.' 826 | } 827 | 828 | # Documentation: If TRUE, the log file is a Unicode text file. If FALSE, the log file is a multibyte code text file. If the file exists, this property is ignored and the current file setting is used. For example, if IsUnicode is FALSE, but the existing file is a Unicode file, then Unicode is used. If IsUnicode is TRUE, but the file is multibyte code, then multibyte code is used. 829 | if (${IsUnicode}) 830 | { 831 | ${NewConsumer}.{IsUnicode} = ${IsUnicode} 832 | Write-Verbose -Message "${CmdletName}: Set the IsUnicode property on LogFileEventConsumer instance"; 833 | } 834 | else 835 | { 836 | Write-Warning -Message "${CmdletName}: `${IsUnicode} parameter was not specified. This warning can generally be safely ignored."; 837 | } 838 | 839 | if (${MaximumFileSize}) 840 | { 841 | ${NewConsumer}.{MaximumFileSize} = ${MaximumFileSize} 842 | Write-Verbose -Message "${CmdletName}: Defined the MaximumFileSize propert of the LogFileEventConsumer instance." 843 | } 844 | else 845 | { 846 | Write-Verbose -Message "${CmdletName}: `${MaximumFileSize} parameter not specified. Default is 65,535." 847 | } 848 | 849 | if (${Text}) 850 | { 851 | ${NewConsumer}.{Text} = ${Text} 852 | Write-Verbose -Message "${CmdletName}: Defined the Text property on the LogFileEventConsumer instance." 853 | } 854 | else 855 | { 856 | Write-Error -Message "${CmdletName}: `${Text} parameter is $null. The Text property MUST be specified on instances of LogFileEventConsumer." 857 | } 858 | 859 | ${PutResult} = ${NewConsumer}.Put() 860 | Write-Verbose -Message "${CmdletName}: Called Put() method on new instance of LogFileEventConsumer" 861 | 862 | Write-Output -InputObject ([wmi]"$(${PutResult}.{Path})") 863 | } 864 | #endregion LogFileEventConsumer 865 | 866 | # (DONE) TODO: Add support for NTEventLogEventConsumer 867 | #region NTEventLogEventConsumer 868 | # If the consumer type is a command line, then we will create an instance of NTEventLogEventConsumer 869 | # Documentation: http://msdn.microsoft.com/en-us/library/aa392715(v=VS.85).aspx 870 | 'EventLog' 871 | { 872 | ${NewConsumer} = ([wmiclass]"\\${ComputerName}\root\subscription:NTEventLogEventConsumer").CreateInstance() 873 | Write-Verbose -Message "${CmdletName}: Created new instance of NTEventLogEventConsumer" 874 | 875 | # Define the Name of the NTEventLogEventConsumer 876 | if (${Name}) 877 | { 878 | ${NewConsumer}.{Name} = ${Name} 879 | Write-Verbose -Message "${CmdletName}: Defined the Name property of NTEventLogEventConsumer instance." 880 | } 881 | else 882 | { 883 | Write-Warning "${CmdletName}: `${Name} parameter not specified. Using random GUID as consumer's name." 884 | } 885 | 886 | # Specify the event type: Information, Error, Warning, etc. 887 | # See the BEGIN { ... } block for a cross-reference, or winnt.h 888 | if (${EventType}) 889 | { 890 | ${NewConsumer}.EventType = ${EventTypes}.$EventType 891 | Write-Verbose -Message "${CmdletName}: Defined the EventType (${EventType},$(${EventTypes}.$EventType))on NTEventLogEventConsumer" 892 | } 893 | else 894 | { 895 | Write-Verbose -Message "${CmdletName}: `${EventType} parameter is $null. The default event type is 1 (Error)." 896 | } 897 | 898 | # EventId has a Not_Null WMI qualifier assigned to it -- user must define this value 899 | # Alternative: Specify a default event ID, so user doesn't have to specify this parameter? 900 | if (${EventId}) 901 | { 902 | ${NewConsumer}.EventId = ${EventId} 903 | Write-Verbose -Message "${CmdletName}: Defined the EventID (${EventId}) property" 904 | } 905 | else 906 | { 907 | Write-Warning -Message "${CmdletName}: `${EventId} parameter is `$null; An EventID must be specified." 908 | } 909 | 910 | # Documentation: Array of standard string templates that is used as the insertion string for an event log record. 911 | if (${InsertionStringTemplates}) 912 | { 913 | ${NewConsumer}.InsertionStringTemplates = ${InsertionStringTemplates} 914 | Write-Verbose -Message 'Defined the InsertionStringTemplates property' 915 | } 916 | else 917 | { 918 | Write-Warning -Message "${CmdletName}: `${InsertionStringTemplates} property is $null; This property must be defined." 919 | } 920 | 921 | if (${UNCServerName}) 922 | { 923 | ${NewConsumer}.UncServerName = ${UNCServerName} 924 | Write-Verbose "${CmdletName}: Set the UNCServerName property on instance of NTEventLogEventConsumer" 925 | } 926 | else 927 | { 928 | Write-Verbose -Message "${CmdletName}: `${UNCServerName} not specified." 929 | } 930 | 931 | if (${SourceName}) 932 | { 933 | ${NewConsumer}.SourceName = ${SourceName} 934 | Write-Verbose "${CmdletName}: Set the SourceName property on instance of NTEventLogEventConsumer" 935 | } 936 | else 937 | { 938 | Write-Warning -Message "${CmdletName}: `${SourceName} parameter not specified." 939 | } 940 | 941 | if (${Category}) 942 | { 943 | ${NewConsumer}.Category = ${Category} 944 | Write-Verbose "${CmdletName}: Set the Category property on instance of NTEventLogEventConsumer" 945 | } 946 | else 947 | { 948 | Write-Warning -Message "${CmdletName}: `${Category} parameter not specified." 949 | } 950 | 951 | # TEST CODE ONLY 952 | # TODO (DONE): IMPORTANT: Remove test code 953 | # ${NewConsumer}.SourceName = 'blah' 954 | # ${NewConsumer}.Category = 1 955 | # END TEST CODE ONLY 956 | 957 | ${PutResult} = ${NewConsumer}.Put() 958 | 959 | if ($?) 960 | { 961 | if ($Error[0].Details.Message -eq 'Illegal null value ') 962 | { 963 | Write-Error -Message "One or more mandatory properties were not specified for NTEventLogEventConsumer." 964 | } 965 | } 966 | Write-Verbose "${CmdletName}: Wrote NTEventLogEventConsumer instance to provider." 967 | 968 | Write-Output -InputObject $([wmi]"$(${PutResult}.{Path})") 969 | } 970 | #endregion NTEventLogEventConsumer 971 | 972 | # If, somehow, an invalid ${ConsumerType} is specified, then throw an exception. 973 | # This shouldn't be possible, because the parameter is being validated against a set. 974 | default 975 | { 976 | throw "Unrecognized WMI event consumer type. Please use one of the following five values: Script, CommandLine, SMTP, LogFile, EventLog" 977 | } 978 | 979 | } #END switch 980 | 981 | # Check to ensure that 982 | if ({PutResult}.{Path}) 983 | { 984 | Write-Error -Message "Failed to commit WMI event consumer instance to provider." 985 | } 986 | } 987 | #endregion New-WmiEventConsumer process block 988 | 989 | #region New-WmiEventConsumer End block 990 | # This is the end block for New-WmiEventConsumer 991 | end 992 | { 993 | Write-Verbose -Message "${CmdletName}: Running END block" 994 | } 995 | #endregion New-WmiEventConsumer End block 996 | } 997 | #endregion New-WmiEventConsumer 998 | 999 | # Export the advanced function for use in the module 1000 | Export-ModuleMember -Function New-WmiEventConsumer 1001 | 1002 | # Set and export an alias for the advanced function 1003 | Set-Alias -Name nwmic -Value New-WmiEventConsumer 1004 | Export-ModuleMember -Alias nwmic -------------------------------------------------------------------------------- /Functions/New-WmiEventFilter.ps1: -------------------------------------------------------------------------------- 1 | # TODO: Check if a filter with the same name already exists, and prompt user if they want to overwrite (use the -Force parameter) 2 | # TODO (DONE): Check if user is an administrator. If not, write an error message informing them of this, and hope they haven't set $ErrorActionPreference to 'SilentlyContinue' :) 3 | 4 | #region New-WmiEventFilter 5 | function New-WmiEventFilter 6 | { 7 | <# 8 | .Synopsis 9 | Creates a new WMI event filter. 10 | 11 | .Description 12 | Creates a new instance of __EventFilter in the specified namespace. This is typically used in concert with an instance of an event consumer, and a __FilterToConsumerBinding. 13 | 14 | .Parameter Name 15 | A unique name for the event filter. If this parameter is not specified, then a random GUID will be used to identify the event filter. It is highly recommended to use a friendly name for event filters, to avoid confusion when managing them in the future. 16 | 17 | .Parameter Namespace 18 | The WMI namespace in which the the event filter will be executed. This is NOT the same as the namespace where the __EventFilter instance will be created. 19 | 20 | .Parameter Query 21 | The WQL event query that the filter will use to poll for events. 22 | 23 | .Parameter QueryLanguage 24 | The language used to write the event query. This will almost always be 'WQL'. 25 | 26 | .Parameter ComputerName 27 | The computer on which to create the WMI event filter. 28 | 29 | .Inputs 30 | None 31 | 32 | .Outputs 33 | A System.Management.ManagementObject, representing an instance of the __EventFilter WMI class. The output can be stored in a variable, and then used with New-WmiFilterToConsumerBinding. 34 | 35 | .Component 36 | Windows Management Instrumentation (WMI) 37 | 38 | .Link 39 | http://trevorsullivan.net 40 | 41 | .Link 42 | http://powershell.artofshell.com 43 | 44 | .Link 45 | http://msdn.microsoft.com/en-us/library/aa392902(VS.85).aspx 46 | 47 | .Link 48 | http://msdn.microsoft.com/en-us/library/aa394639(VS.85).aspx 49 | 50 | .Link 51 | http://www.codeproject.com/KB/system/PermEvtSubscriptionMOF.aspx?display=Print 52 | #> 53 | 54 | [CmdletBinding( 55 | SupportsShouldProcess = $false 56 | , SupportsTransactions = $false # Script cmdlets cannot support transactions. Only compiled cmdlets can support them. 57 | , ConfirmImpact = 'Low' # This function has a minimal impact on data loss 58 | )] 59 | 60 | #region New-WmiEventFilter Parameters 61 | param( 62 | [Parameter( 63 | Mandatory = $false 64 | , Position = 1 65 | , HelpMessage = "Please enter a name for the event filter." 66 | )] 67 | [string] 68 | [alias("FilterName", "fltr")] 69 | ${Name} 70 | , 71 | # TODO: Use script validation to ensure that this namespace is valid 72 | [Parameter( 73 | Mandatory = $false 74 | , Position = 0 75 | , HelpMessage = "Please specify the namespace where the event query should be executed against." 76 | )] 77 | ${EventNamespace} = 'root\cimv2' 78 | , 79 | [Parameter( 80 | Mandatory = $true 81 | , ParameterSetName = 'WqlQuery' 82 | , HelpMessage = "Please specify the WQL event query to be used for this event filter." 83 | )] 84 | [string] 85 | [alias("WQLQuery", "qry")] 86 | ${Query} 87 | , 88 | # This parameter MUST be set to 'WQL' 89 | [parameter( 90 | Mandatory = $false 91 | , HelpMessage = "Please specify the query language for this event filter; Must be 'WQL'." 92 | )] 93 | [ValidateSet("WQL")] 94 | [string] 95 | ${QueryLanguage} = 'WQL' 96 | , 97 | [Parameter( 98 | Mandatory = $false 99 | , HelpMessage = "Please specify the computer to create the WMI event filter on." 100 | )] 101 | [string] 102 | ${ComputerName} = '.' 103 | , 104 | [Parameter( 105 | Mandatory = $false 106 | , HelpMessage = "Please specify the namespace where the __EventFilter instance should be created." 107 | )] 108 | <# 109 | This [ValidateScript()] block ensures that the user has passed a valid namespace to the function. 110 | UPDATE: After testing, this won't work, because we can't use ${ComputerName} to test a namespace on a remote system. 111 | This validation code will have to go in the BEGIN { ... } block 112 | [ValidateScript({ 113 | Write-Verbose -Message ${ComputerName} 114 | if (([wmiclass]"\\${ComputerName}\root\cimv2:__ThisNamespace").__namespace -eq $_) 115 | { 116 | return $true 117 | } 118 | else 119 | { 120 | return $false 121 | } 122 | })] 123 | #> 124 | [ValidateSet("root\subscription")] 125 | ${Namespace} = 'root\subscription' 126 | 127 | # TODO: Build a new parameter set ( call it "QueryBuilder"?) to allow for query building. Include parameters such as: 128 | # "ClassName" = ex. Win32_Process, Win32_ProcessStartTrace 129 | # If "ClassName" is implemented, use the [ValidateScript()] attribute to ensure the class exists 130 | # "EventType" = Intrinsic or Extrinsic -- alternative: write some code to automatically detect this based on the ClassName? 131 | # "PollingInterval" = the polling interval for the WITHIN clause of the event query 132 | ) 133 | #endregion New-WmiEventFilter Parameters 134 | 135 | #region New-WmiEventFilter Begin block 136 | begin 137 | { 138 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name 139 | Write-Verbose -Message "${CmdletName}: Running the BEGIN block" 140 | 141 | #region Check if user token is an administrator 142 | ${Identity} = [System.Security.Principal.WindowsIdentity]::GetCurrent() 143 | ${Principal} = new-object System.Security.Principal.WindowsPrincipal(${Identity}) 144 | ${IsAdmin} = $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) 145 | if (-not ${IsAdmin}) 146 | { 147 | Write-Error -Message "${CmdletName}: User is not an administrator. Cannot continue." -RecommendedAction "${CmdletName}: Please run this function as an administrator." 148 | } 149 | #endregion Check if user token is an administrator 150 | 151 | #region Check for existence of ${EventNamespace} and ${Namespace} 152 | if (([wmiclass]"\\${ComputerName}\${EventNamespace}:__ThisNamespace").__namespace -eq ${EventNamespace}) 153 | { 154 | Write-Verbose -Message "${CmdletName}: Validated the existence of WMI namespace passed to `${EventNamespace} (\\${ComputerName}\${EventNamespace})" 155 | } 156 | else 157 | { 158 | Write-Error -Message "${CmdletName}: Could not validate the existence of WMI namespace passed to `${EventNamespace} (\\${ComputerName}\${EventNamespace})" -TargetObject ${EventNamespace} -ErrorAction Stop 159 | } 160 | 161 | if (([wmiclass]"\\${ComputerName}\${Namespace}:__ThisNamespace").__namespace -eq ${Namespace}) 162 | { 163 | Write-Verbose -Message "${CmdletName}: Validated the existence of WMI namespace passed to `${Namespace} (\\${ComputerName}\${Namespace})" 164 | } 165 | else 166 | { 167 | Write-Error -Message "${CmdletName}: Could not validate the existence of WMI namespace passed to `${Namespace} (\\${ComputerName}\${Namespace})" -TargetObject ${Namespace} -ErrorAction Stop 168 | } 169 | #endregion Check for existence of ${EventNamespace} and ${Namespace} 170 | 171 | #region Check for existing __EventFilter with same name 172 | # Check to see if an instance of __EventFilter with the requested name already exists 173 | if (${Name}) 174 | { 175 | Write-Verbose -Message "Looking for existing instances of __EventFilter in namespace ${Namespace} with the name ${Name}" 176 | ${ExistingFilter} = Get-WmiObject -Namespace ${Namespace} -ComputerName ${ComputerName} -Class __EventFilter -Filter "Name = '${Name}'" 177 | if (${ExistingFilter}) 178 | { 179 | Write-Warning -Message "${CmdletName}: __EventFilter instance already exists with name ${Name}" 180 | #Write-Output -InputObject ${ExistingFilter} 181 | } 182 | } 183 | #endregion Check for existing __EventFilter with same name 184 | } 185 | #endregion New-WmiEventFilter Begin block 186 | 187 | #region New-WmiEventFilter Process block 188 | process 189 | { 190 | ${NewFilter} = ([wmiclass]"\\${ComputerName}\${Namespace}:__EventFilter").CreateInstance() 191 | Write-Verbose -Message "${CmdletName}: Created new instance of __EventFilter" 192 | 193 | # The QueryLanguage will always be 'WQL' for WMI event queries 194 | ${NewFilter}.{QueryLanguage} = ${QueryLanguage} 195 | Write-Verbose -Message "${CmdletName}: Defined the QueryLanguage property" 196 | 197 | # The WQL event query that will be used to capture events 198 | if (${NewFilter}) 199 | { 200 | ${NewFilter}.{Query} = ${Query} 201 | Write-Verbose -Message "${CmdletName}: Defined the Query (${Query}) property" 202 | } 203 | 204 | # The namespace that events will be captured in. 205 | # Example: root\cimv2, if your event query targets Win32_Process 206 | if (${EventNamespace}) 207 | { 208 | ${NewFilter}.{EventNamespace} = ${EventNamespace} 209 | Write-Verbose -Message "${CmdletName}: Defined the EventNamespace (${EventNamespace}) property" 210 | } 211 | else 212 | { 213 | Write-Warning -Message "${CmdletName}: `${EventNamespace} parameter was not specified." -WarningAction "Please specify a valid WMI namespace" 214 | } 215 | 216 | # The unique name for the event filter instance 217 | if (${Name}) 218 | { 219 | ${NewFilter}.{Name} = ${Name} 220 | Write-Verbose -Message "${CmdletName}: Defined the Name (${Name}) property" 221 | } 222 | else 223 | { 224 | Write-Verbose "${CmdletName}: `${Name} parameter was not specified. Defaulting to random GUID for Name property." 225 | } 226 | 227 | # Write the __EventFilter instance to the WMI provider 228 | Write-Verbose -Message "${CmdletName}: Preparing to commit __EventFilter instance to WMI: ${PutResult}" 229 | ${PutResult} = ${NewFilter}.Put() 230 | 231 | if (${PutResult}.Path) 232 | { 233 | Write-Verbose -Message ('${CmdletName}: Committed new __EventFilter instance: ' + ${PutResult}.{Path}) 234 | # Write new __EventFilter instance to the pipeline 235 | Write-Output $([wmi]"$(${PutResult}.{Path})") 236 | } 237 | else 238 | { 239 | Write-Error -Message "${CmdletName}: Failed to commit __EventFilter instance to WMI." -ErrorAction Stop 240 | } 241 | 242 | } 243 | #endregion New-WmiEventFilter Process block 244 | 245 | #region New-WmiEventFilter End block 246 | end 247 | { 248 | Write-Verbose -Message "${CmdletName}: Running the END block" 249 | } 250 | #endregion New-WmiEventFilter End block 251 | } 252 | #endregion New-WmiEventFilter 253 | 254 | # Export the advanced function for use in the module 255 | Export-ModuleMember -Function New-WmiEventFilter 256 | 257 | # Create and export an alias for the advanced function 258 | Set-Alias -Name nwmif -Value New-WmiEventFilter 259 | Export-ModuleMember -Alias nwmif -------------------------------------------------------------------------------- /Functions/New-WmiFilterToConsumerBinding.ps1: -------------------------------------------------------------------------------- 1 | # TODO: Test creation of a new __FilterToConsumerBinding instance against a remote computer 2 | # TODO: Rename this cmdlet to New-WmiEventBinding for consistency? 3 | 4 | <# 5 | .Synopsis 6 | Creates a new binding between a WMI event filter and a WMI event consumer. 7 | 8 | .Description 9 | Creates a new binding between a WMI event filter and a WMI event consumer. 10 | 11 | .Parameter ComputerName 12 | The computer name to perform the operation against. 13 | 14 | .Parameter Namespace 15 | The WMI namespace to create the instance of __FilterToConsumerBinding in. 16 | 17 | .Parameter Filter 18 | The WMI event filter instance to use for the permanent event filter/consumer binding. 19 | 20 | .Parameter Consumer 21 | The WMI event consumer instance to use for the permanent event filter/consumer binding. 22 | 23 | .Parameter SlowDownProviders 24 | A boolean value that determines whether or not WMI will slow down providers in order to keep up with event processing. NOT RECOMMENDED TO ENABLE! 25 | 26 | .Inputs 27 | No inputs available. Piping objects to New-WmiFilterToConsumerBinding is not possible. 28 | 29 | .Outputs 30 | A System.Management.ManagementObject representing the new __FilterToConsumerBinding WMI instance. 31 | 32 | .Link 33 | http://trevorsullivan.net 34 | 35 | .Link 36 | http://powershell.artofshell.com 37 | #> 38 | function New-WmiFilterToConsumerBinding 39 | { 40 | [CmdletBinding( 41 | SupportsShouldProcess = $false 42 | , SupportsTransactions = $false 43 | , ConfirmImpact = 'Low' 44 | )] 45 | 46 | #region New-WmiFilterToConsumerBinding Parameters 47 | param( 48 | [parameter( 49 | Mandatory = $false 50 | , HelpMessage = "Please specify the computer name to create the binding on." 51 | )] 52 | [string] 53 | ${ComputerName} = 'localhost' 54 | , 55 | [parameter( 56 | Mandatory = $false 57 | , HelpMessage = "Please specify the namespace where you would like to create the filter/consumer binding." 58 | )] 59 | [ValidateSet("root\subscription")] 60 | [string] 61 | ${Namespace} = 'root\subscription' 62 | , 63 | [parameter( 64 | Mandatory = $true 65 | , HelpMessage = "Please specify the WMI __EventFilter instance to use for this binding." 66 | , ValueFromPipelineByPropertyName = $true 67 | )] 68 | [alias("WmiFilter")] 69 | [ValidateNotNull()] 70 | [System.Management.ManagementObject] 71 | ${Filter} 72 | , 73 | [parameter( 74 | Mandatory = $true 75 | , HelpMessage = "Please specify the WMI event consumer for this binding." 76 | , ValueFromPipelineByPropertyName = $true 77 | )] 78 | [alias("EventConsumer", "WmiEventConsumer")] 79 | [ValidateNotNull()] 80 | [System.Management.ManagementObject] 81 | ${Consumer} 82 | , 83 | [parameter( 84 | Mandatory = $false 85 | , HelpMessage = 'Please specify whether or not to maintain security context.' 86 | )] 87 | [bool] 88 | ${MaintainSecurityContext} = $false 89 | , 90 | 91 | [parameter( 92 | Mandatory = $false 93 | , HelpMessage = "Please specify whether or not to slow down WMI providers in order to keep up with event handling. NOT RECOMMENDED!" 94 | )] 95 | [bool] 96 | ${SlowDownProviders} = $false 97 | ) 98 | #endregion New-WmiFilterToConsumerBinding Parameters 99 | 100 | #region New-WmiFilterToConsumerBinding BEGIN block 101 | begin 102 | { 103 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name 104 | Write-Verbose -Message ('{0}: Start running BEGIN block' -f ${CmdletName}); 105 | # TODO: Validate WMI instance paths passed to ${Filter} and ${Consumer} parameters 106 | 107 | # TODO: Validate that the ${Namespace} is valid on the ${ComputerName} specified (test bind) 108 | } 109 | #endregion New-WmiFilterToConsumerBinding BEGIN block 110 | 111 | #region New-WmiFilterToConsumerBinding PROCESS block 112 | process 113 | { 114 | Write-Verbose -Message "${CmdletName}: Start running PROCESS block"; 115 | 116 | # Create new in-memory instance of __FilterToConsumerBinding 117 | ${NewBinding} = ([wmiclass]"\\${ComputerName}\${Namespace}:__FilterToConsumerBinding").CreateInstance() 118 | 119 | # Cannot use braces around the Filter property name, otherwise PowerShell complains. Filter is a keyword in PowerShell 120 | if (${Filter}) 121 | { 122 | ${NewBinding}.Filter = ${Filter}.__PATH 123 | Write-Verbose -Message ("${CmdletName}: Defined the Filter property: " + ${Filter}.__PATH) 124 | } 125 | else 126 | { 127 | Write-Error -Message 'New-WmiFilterToConsumerBinding: ${Filter} parameter is $null. You must specify a valid instance of __EventFilter to the ${Filter} parameter of this function.' 128 | } 129 | 130 | # Write-Host ${Consumer}.GetType() 131 | Write-Debug -Message ("${CmdletName}: Consumer is of type: " + ${Consumer}.GetType()) 132 | # A reference to the __EventConsumer (parent class) of the WMI event consumer 133 | if (${Consumer}) 134 | { 135 | ${NewBinding}.{Consumer} = ${Consumer}.__PATH 136 | Write-Verbose -Message ("${CmdletName}: Defined the Consumer property: " + ${Consumer}.__PATH) 137 | } 138 | # If the event consumer is $null, we can't continue with creating the __FilterToConsumerBinding instance 139 | else 140 | { 141 | Write-Error -Message ('{0}: ${Consumer} is $null. Unable to continue. Please get a reference to a WMI event consumer, or create a new one. Once you have an instance of __EventConsumer, please pass it to this function as the -Consumer parameter.' -f ${CmdletName}); 142 | } 143 | 144 | ${NewBinding}.{MaintainSecurityContext} = ${MaintainSecurityContext}; 145 | ${NewBinding}.{SlowDownProviders} = ${SlowDownProviders}; 146 | 147 | ${PutResult} = ${NewBinding}.Put() 148 | Write-Verbose -Message ('{0}: Wrote __FilterToConsumerBinding instance to WMI provider.' -f ${CmdletName}); 149 | } 150 | #endregion New-WmiFilterToConsumerBinding PROCESS block 151 | 152 | #region New-WmiFilterToConsumerBinding END block 153 | end 154 | { 155 | Write-Verbose -Message ('{0}: Start running END block' -f ${CmdletName}); 156 | } 157 | #endregion New-WmiFilterToConsumerBinding END block 158 | } 159 | 160 | # Export the Get-WmiFilterToConsumerBinding function 161 | Export-ModuleMember -Function New-WmiFilterToConsumerBinding; 162 | 163 | # Create and export alias for the function 164 | New-Alias -Name nwmib -Value New-WmiFilterToConsumerBinding; 165 | Export-ModuleMember -Alias nwmib; -------------------------------------------------------------------------------- /Functions/Remove-WmiEventBinding.ps1: -------------------------------------------------------------------------------- 1 | # TODO: Test what happens if you delete an __EventFilter instance while the __FilterToConsumerBinding instance still exists 2 | 3 | function Remove-WmiEventBinding 4 | { 5 | <# 6 | .Synopsis 7 | Removes a WMI event binding. 8 | 9 | .Description 10 | Removes a binding between a WMI event filter and a WMI event consumer. This function requires the input of a partial filter name and consumer name. These two parameters will be used to identify the binding instance to be removed, because __FilterToConsumerBinding does not provider a friendly "Name" property to identify them by. 11 | 12 | .Parameter FilterName 13 | Partial name of the event filter that the binding is using. 14 | 15 | .Parameter ConsumerName 16 | Partial name of the event consumer that the binding is using. 17 | 18 | .Component 19 | Windows Management Instrumentation (WMI) 20 | 21 | .Link 22 | http://trevorsullivan.net 23 | 24 | .Link 25 | http://powershell.artofshell.com 26 | #> 27 | 28 | param( 29 | [Parameter( 30 | Mandatory = $false 31 | , HelpMessage = 'Please enter the WMI namespace where the __FilterToConsumerBinding instance exists.' 32 | )] 33 | [string] 34 | $Namespace = 'root\subscription' 35 | , 36 | [Parameter( 37 | Mandatory = $false 38 | , HelpMessage = 'Please enter the Name of the WMI filter that the binding will be removed for.' 39 | # , ParameterSetName = 'filter' 40 | )] 41 | [string] 42 | ${Filter} 43 | , 44 | [Parameter( 45 | Mandatory = $false 46 | , HelpMessage = 'Please enter the WMI namespace where the __FilterToConsumerBinding instance exists.' 47 | # , ParameterSetName = 'consumer' 48 | )] 49 | [string] 50 | ${Consumer} 51 | , 52 | [string] 53 | ${ConsumerNamespace} = 'root\subscription' 54 | , 55 | [string] 56 | ${FilterNamespace} = 'root\subscription' 57 | , 58 | [Parameter(ValueFromPipelineByPropertyName = $true)] 59 | [ValidateScript({ 60 | if (Test-Connection -ComputerName $_ -Count 1) { $true; } 61 | else { $false; } 62 | })] 63 | [string] 64 | ${ComputerName} = '.' 65 | ) 66 | 67 | begin { 68 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name; 69 | ${ParameterSetName} = $Pscmdlet.ParameterSetName; 70 | Write-Verbose -Message ('{0}: Start running BEGIN block' -f $CmdletName); 71 | 72 | <# 73 | # Replace wildcards (*) with WMI wildcards (%) 74 | if (${Filter}) { 75 | ${Filter} = ${Filter}.Replace('*','%'); 76 | } 77 | 78 | # Replace wildcards (*) with WMI wildcards (%) 79 | if (${Consumer}) { 80 | ${Consumer} = ${Consumer}.Replace('*','%'); 81 | } 82 | #> 83 | } 84 | 85 | process { 86 | Write-Verbose -Message ('{0}: Start running PROCESS block' -f $CmdletName); 87 | 88 | $Consumer = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${ConsumerNamespace} -Filter ("Name = '{0}'" -f ${Consumer}) -ErrorAction SilentlyContinue; 89 | $Filter = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${FilterNamespace} -Filter ("Name = '{0}'" -f ${Filter}) -ErrorAction SilentlyContinue; 90 | 91 | $ConsumerRefQuery = 'REFERENCES OF {{0}} WHERE __CLASS = ''__FilterToConsumerBinding''' -f $Consumer.__PATH; 92 | $ConsumerRefList = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${Namespace} -Query $ConsumerRefQuery; 93 | 94 | $FilterRefQuery = 'REFERENCES OF {{0}} WHERE __CLASS = ''__FilterToConsumerBinding''' -f $Filter.__PATH; 95 | $FilterRefList = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${Namespace} -Query $FilterRefQuery; 96 | } 97 | 98 | end 99 | { 100 | Write-Verbose -Message ('{0}: Start running END block' -f $CmdletName); 101 | } 102 | } 103 | 104 | # Export the Remove-WmiEventBinding function 105 | Export-ModuleMember -Function Remove-WmiEventBinding; 106 | 107 | # Create an alias for the advanced function and export it 108 | Set-Alias -Name rmwmib -Value Remove-WmiEventBinding; 109 | Export-ModuleMember -Alias rmwmib; -------------------------------------------------------------------------------- /Functions/Remove-WmiEventConsumer.ps1: -------------------------------------------------------------------------------- 1 | # TODO: Support for piping input [String[]] -- map pipeline input to ${Name} parameter? 2 | 3 | 4 | function Remove-WmiEventConsumer 5 | { 6 | <# 7 | .Synopsis 8 | Deletes a WMI event consumer from the specified computer name and WMI namespace. 9 | 10 | .Parameter ComputerName 11 | The name of the computer that the WMI event consumer will be removed from. 12 | 13 | .Parameter Name 14 | The name of the WMI event consumer that will be removed. 15 | 16 | .Parameter ConsumerType 17 | The type of WMI event consumer that will be removed. 18 | #> 19 | 20 | [CmdletBinding()] 21 | 22 | param( 23 | [Parameter(ValueFromPipelineByPropertyName = $true)] 24 | [string] 25 | ${Name} = '' 26 | , 27 | [Parameter(ValueFromPipelineByPropertyName = $true)] 28 | [string] 29 | ${Namespace} = 'root\subscription' 30 | , 31 | [Parameter(ValueFromPipelineByPropertyName = $true)] 32 | [ValidateScript({ 33 | if (Test-Connection -ComputerName $_ -Count 1) { $true; } 34 | else { $false; } 35 | })] 36 | [string] 37 | ${ComputerName} = '.' 38 | , 39 | # In the interest of think + type, I've adjusted these types from their actual WMI class names 40 | # EventLog = NTEventLogEventConsumer 41 | # LogFile = LogFileEventConsumer 42 | # Script = ActiveScriptEventConsumer 43 | # CommandLine = CommandLineEventConsumer 44 | # SMTP = SMTPEventConsumer 45 | [Parameter(ValueFromPipelineByPropertyName = $true)] 46 | [ValidateSet('CommandLine', 'EventLog', 'LogFile', 'Script', 'SMTP')] 47 | [string] 48 | ${ConsumerType} 49 | ) 50 | 51 | begin { 52 | # Get the cmdlet name for writing dynamic log messages 53 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name 54 | 55 | Write-Verbose -Message "${CmdletName}: Start running BEGIN block"; 56 | 57 | $ConsumerTypeList = @{ 58 | CommandLine = 'CommandLineEventConsumer'; 59 | EventLog = 'NTEventLogEventConsumer'; 60 | LogFile = 'LogFileEventConsumer'; 61 | Script = 'ActiveScriptEventConsumer'; 62 | SMTP = 'SMTPEventConsumer'; 63 | } 64 | } 65 | 66 | process 67 | { 68 | Write-Verbose -Message "${CmdletName}: Start running PROCESS block"; 69 | 70 | $ConsumerClass = $ConsumerTypeList.$ConsumerType; 71 | Write-Verbose -Message ('{0}: Consumer type is: {1}' -f $CmdletName, $ConsumerType); 72 | $Consumer = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${Namespace} -Class $ConsumerClass -Filter ("Name = '{0}'" -f ${Name}); 73 | 74 | if ($Consumer) { 75 | try { 76 | $Consumer.Delete(); 77 | } 78 | catch { 79 | Write-Error -Exception $_ -Message ('{0}: Failed to delete consumer with name: {1}' -f ${CmdletName}, ${Name}); 80 | } 81 | } 82 | } 83 | 84 | end 85 | { 86 | Write-Verbose -Message "${CmdletName}: Start running END block"; 87 | } 88 | } 89 | 90 | # Export the Remove-WmiEventConsumer function 91 | Export-ModuleMember Remove-WmiEventConsumer 92 | 93 | # Create and export an alias for the function 94 | New-Alias -Name rwmic -Value Remove-WmiEventConsumer; 95 | Export-ModuleMember -Alias rwmic; -------------------------------------------------------------------------------- /Functions/Remove-WmiEventFilter.ps1: -------------------------------------------------------------------------------- 1 | function Remove-WmiEventFilter { 2 | <# 3 | .Synopsis 4 | Removes a WMI event filter, with the specified name. 5 | 6 | .Parameter Name 7 | The name of the WMI event filter that will be removed. 8 | 9 | .Parameter Namespace 10 | The WMI namespace where the WMI event filter resides. 11 | 12 | .Parameter ComputerName 13 | The name of the computer where the WMI event filter will be removed from. 14 | 15 | .Link 16 | http://trevorsullivan.net 17 | #> 18 | [CmdletBinding()] 19 | param ( 20 | [Parameter(ValueFromPipelineByPropertyName = $true)] 21 | [string] 22 | ${Name} 23 | , 24 | [Parameter(ValueFromPipelineByPropertyName = $true)] 25 | [Alias('ns', 'WMINamespace')] 26 | [string] 27 | ${Namespace} = 'root\subscription' 28 | , 29 | [Parameter(ValueFromPipelineByPropertyName = $true)] 30 | [Alias('cn')] 31 | [ValidateScript({ 32 | if (Test-Connection -ComputerName $_ -Count 1) { $true; } 33 | else { $false; } 34 | })] 35 | [string] 36 | ${ComputerName} = '.' 37 | ) 38 | 39 | begin { 40 | # Get the cmdlet name for writing dynamic log messages 41 | ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name 42 | 43 | Write-Verbose -Message "${CmdletName}: Start running BEGIN block"; 44 | } 45 | 46 | process { 47 | Write-Verbose -Message "${CmdletName}: Start running PROCESS block"; 48 | 49 | $Filter = Get-WmiObject -ComputerName ${ComputerName} -Namespace ${Namespace} -Class __EventFilter -Filter ("Name = '{0}'" -f ${Name}); 50 | 51 | if ($Filter) { 52 | try { 53 | $Filter.Delete(); 54 | } 55 | catch { 56 | Write-Error -Exception $_ -Message ('{0}: Failed to delete WMI event filter named ({1})' -f ${CmdletName}, ${Name}); 57 | } 58 | } 59 | else { 60 | Write-Error -Message ('{0}: No WMI event filter found with name {1}' -f ${CmdletName}, ${Name}); 61 | } 62 | } 63 | 64 | end { 65 | Write-Verbose -Message "${CmdletName}: Start running END block"; 66 | } 67 | } 68 | 69 | # Export the function 70 | Export-ModuleMember -Function Remove-WmiEventFilter; 71 | 72 | # Create and export an alias 73 | New-Alias -Name rmwmif -Value Remove-WmiEventFilter; 74 | Export-ModuleMember -Alias rmwmif; -------------------------------------------------------------------------------- /Functions/Set-ScriptingStandardConsumerSetting.ps1: -------------------------------------------------------------------------------- 1 | # TODO: Add support for configuring the ActiveScriptEventConsumer 2 | # http://msdn.microsoft.com/en-us/library/aa393255(v=VS.85).aspx 3 | 4 | <# 5 | .Synopsis 6 | Configures the ActiveScriptEventConsumer class using the ScriptingStandardConsumerSetting class. 7 | 8 | .Description 9 | Configures the ActiveScriptEventConsumer class using the ScriptingStandardConsumerSetting class. 10 | 11 | .Link 12 | http://trevorsullivan.net 13 | 14 | .Link 15 | http://powershell.artofshell.com 16 | #> 17 | function Set-ScriptingStandardConsumerSetting 18 | { 19 | begin 20 | { 21 | } 22 | 23 | process 24 | { 25 | } 26 | 27 | end 28 | { 29 | } 30 | } 31 | 32 | Export-ModuleMember Set-ScriptingStandardConsumerSetting -------------------------------------------------------------------------------- /Functions/Test-Get-WmiEventConsumer.ps1: -------------------------------------------------------------------------------- 1 | Remove-Module -Name PowerEvents -ErrorAction SilentlyContinue 2 | Import-Module -Name PowerEvents -ErrorAction SilentlyContinue 3 | 4 | $VerbosePreference = 'continue' 5 | $DebugPreference = 'continue' 6 | 7 | Get-WmiEventConsumer -ConsumerType Script -Name *b* -Verbose -------------------------------------------------------------------------------- /Functions/Test-Get-WmiEventFilter.ps1: -------------------------------------------------------------------------------- 1 | Clear 2 | Remove-Module -Name PowerEvents -ErrorAction SilentlyContinue 3 | Import-Module -Name PowerEvents -ErrorAction SilentlyContinue 4 | 5 | $VerbosePreference = 'continue' 6 | $DebugPreference = 'continue' 7 | 8 | Get-WmiEventFilter -Name Matt -------------------------------------------------------------------------------- /Functions/Test-IsAdministrator.ps1: -------------------------------------------------------------------------------- 1 | function Test-IsAdministrator { 2 | <# 3 | .Synopsis 4 | Determines whether or not the user is a member of the local Administrators security group. 5 | 6 | .Outputs 7 | System.Bool 8 | #> 9 | [CmdletBinding()] 10 | param ( 11 | ) 12 | 13 | ${Identity} = [System.Security.Principal.WindowsIdentity]::GetCurrent() 14 | ${Principal} = new-object System.Security.Principal.WindowsPrincipal(${Identity}) 15 | ${IsAdmin} = $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) 16 | 17 | Write-Output -InputObject ${IsAdmin}; 18 | } -------------------------------------------------------------------------------- /Install Module.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Author 3 | Trevor Sullivan 4 | 5 | .Date 6 | January 30th, 2012 7 | 8 | .Purpose 9 | The purpose of this script is to import a PowerShell module from wherever it 10 | resides on the filesystem. To use this script, simply copy it to the root of 11 | your module's folder, and execute it. Your working directory doesn't matter. 12 | 13 | Using this script avoids the need to copy your module to a valid path in the 14 | $env:PSModulePath Windows environment variable. That way, if your module is 15 | part of a source control repository, which may reside outside of the default 16 | paths defined in $env:PSModulePath, you can easily load the module without 17 | the need to copy your module files to your default modules folder. 18 | 19 | Note: This script requires that the module folder name match the module name 20 | 21 | #> 22 | 23 | 24 | # Get the path the script is executing from 25 | $ScriptPath = Split-Path -Path $MyInvocation.MyCommand.Path -Parent; 26 | Write-Debug -Message ("Install module script is running from: {0}" -f $ScriptPath); 27 | # Get just the 'leaf' folder name of the script's execution path 28 | $ModuleName = Split-Path -Path $ScriptPath -Leaf; 29 | 30 | # Get the parent of the script path, which will be the newly added module search path 31 | $ModulePath = Split-Path -Path $ScriptPath -Parent; 32 | 33 | Write-Debug -Message ('$env:PSModulePath is set to: {0}' -f $env:PSModulePath); 34 | 35 | # If $env:PSModulePath does not contain the new module path, then add it 36 | if ($env:PSModulePath.Split(';') -notcontains $ModulePath) { 37 | $env:PSModulePath = $env:PSModulePath + (';{0}' -f $ModulePath); 38 | } 39 | 40 | # Silently remove the module, in case it is loaded 41 | Remove-Module -Name $ModuleName -ErrorAction SilentlyContinue; 42 | # Load the module 43 | $Module = Import-Module -Name $ModuleName -PassThru; 44 | 45 | 46 | # Clean up 47 | Remove-Variable -Name Module, ModulePath, ModuleName, ScriptPath; 48 | $Module = $ModulePath = $ModuleName = $ScriptPath = $null; -------------------------------------------------------------------------------- /PowerEvents.psd1: -------------------------------------------------------------------------------- 1 | @{ 2 | 3 | # Script module or binary module file associated with this manifest 4 | RootModule = 'PowerEvents.psm1' 5 | 6 | # Version number of this module. 7 | ModuleVersion = '0.4' 8 | 9 | # ID used to uniquely identify this module 10 | GUID = '53d3dd2e-2555-423e-b355-e84b712ae00a' 11 | 12 | # Author of this module 13 | Author = 'Trevor Sullivan ' 14 | 15 | # Company or vendor of this module 16 | CompanyName = 'Trevor Sullivan' 17 | 18 | # Copyright statement for this module 19 | Copyright = '(c) 2010-2014 Trevor Sullivan. All rights reserved.' 20 | 21 | # Description of the functionality provided by this module 22 | Description = 'PowerEvents allow administrators to create permanent event subscriptions in the Microsoft Windows Management Instrumentation (WMI) service.' 23 | 24 | # Minimum version of the Windows PowerShell engine required by this module 25 | PowerShellVersion = '3.0' 26 | 27 | # Name of the Windows PowerShell host required by this module 28 | # PowerShellHostName = '' 29 | 30 | # Minimum version of the Windows PowerShell host required by this module 31 | # PowerShellHostVersion = '' 32 | 33 | # Minimum version of the .NET Framework required by this module 34 | # DotNetFrameworkVersion = '' 35 | 36 | # Minimum version of the common language runtime (CLR) required by this module 37 | # CLRVersion = '' 38 | 39 | # Processor architecture (None, X86, Amd64) required by this module 40 | # ProcessorArchitecture = '' 41 | 42 | # Modules that must be imported into the global environment prior to importing this module 43 | # RequiredModules = @() 44 | 45 | # Assemblies that must be loaded prior to importing this module 46 | # RequiredAssemblies = @() 47 | 48 | # Script files (.ps1) that are run in the caller's environment prior to importing this module 49 | # ScriptsToProcess = @() 50 | 51 | # Type files (.ps1xml) to be loaded when importing this module 52 | # TypesToProcess = @() 53 | 54 | # Format files (.ps1xml) to be loaded when importing this module 55 | # FormatsToProcess = @() 56 | 57 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 58 | # NestedModules = @() 59 | 60 | # Functions to export from this module 61 | FunctionsToExport = '*' 62 | 63 | # Cmdlets to export from this module 64 | # CmdletsToExport = '*' 65 | 66 | # Variables to export from this module 67 | VariablesToExport = '*' 68 | 69 | # Aliases to export from this module 70 | AliasesToExport = '*' 71 | 72 | # List of all modules packaged with this module 73 | # ModuleList = @() 74 | 75 | # List of all files packaged with this module 76 | # FileList = @() 77 | 78 | # Private data to pass to the module specified in RootModule/ModuleToProcess 79 | # PrivateData = '' 80 | 81 | # HelpInfo URI of this module 82 | # HelpInfoURI = '' 83 | 84 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 85 | # DefaultCommandPrefix = '' 86 | 87 | } -------------------------------------------------------------------------------- /PowerEvents.psm1: -------------------------------------------------------------------------------- 1 | function Write-Introduction 2 | { 3 | Write-Host "Thank you for installing the $($PowerEvents.ModuleName) module!" 4 | Write-Host "".PadLeft(40, "=") 5 | 6 | } 7 | 8 | # TODO: Build a Windows Installer (MSI) package for PowerEvents 9 | 10 | # Define the name of the module 11 | # Build a hashtable with basic properties for use elsewhere in the module 12 | $Global:PowerEvents = @{ 13 | ModuleName = "PowerEvents" 14 | } 15 | 16 | #region Get script path 17 | $MyInvocation.MyCommand.Path 18 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 19 | #Write-Host "Script path is: ${ScriptPath}" 20 | #endregion 21 | 22 | Write-Host -Object ('Loading PowerShell module: {0}' -f $PowerEvents.ModuleName); 23 | 24 | #region Check admin rights 25 | # Check if user token is an administrator 26 | 27 | . ${ScriptPath}\Functions\Test-IsAdministrator.ps1; 28 | 29 | if (-not (Test-IsAdministrator)) 30 | { 31 | Write-Error -Message 'User is not an administrator. Module installation cannot continue.' -RecommendedAction 'Please import this module as an administrator.'; 32 | # Remove-Module $PowerEvents.ModuleName 33 | return; 34 | } 35 | #endregion Check admin rights 36 | 37 | #region Dot-source cmdlet scripts 38 | # Dot-source supporting scripts 39 | try 40 | { 41 | ${ScriptList} = @( 42 | 'New-WmiEventFilter.ps1' 43 | , 'New-WmiEventConsumer.ps1' 44 | , 'New-WmiFilterToConsumerBinding.ps1' 45 | , 'Get-WmiEventConsumer.ps1' 46 | , 'Get-WmiEventFilter.ps1' 47 | , 'Get-WmiEventBinding.ps1' 48 | , 'Remove-WmiEventConsumer.ps1' 49 | , 'Remove-WmiEventFilter.ps1' 50 | , 'Remove-WmiEventBinding.ps1' 51 | ); 52 | 53 | foreach (${Script} in ${ScriptList}) { 54 | . ${ScriptPath}\Functions\${Script}; 55 | } 56 | } 57 | catch 58 | { 59 | Write-Error -Exception $_ -Message "$($PowerEvents.ModuleName): Error occurred while loading module functions."; 60 | } 61 | 62 | #endregion 63 | 64 | # Call the function to write some help to the screen 65 | # TODO: Implement this function. Commenting out for initial release 66 | # Write-Introduction 67 | 68 | Write-Host "Finished loading PowerShell module: $($PowerEvents.ModuleName)" 69 | 70 | # TODO: Create a module manifest 71 | <# 72 | New-ModuleManifest ` 73 | -Author 'Trevor Sullivan' ` 74 | -CmdletsToExport * ` 75 | -FileList $(Get-ChildItem *) ` 76 | -Copyright 'Trevor Sullivan' ` 77 | -CompanyName 'Trevor Sullivan' 78 | 79 | #> -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **IMPORTANT**: To get started: 2 | 3 | 1. Please read the documentation included in the module folder 4 | 2. Watch the [YouTube videos](https://www.youtube.com/playlist?list=PLDbRgZ0OOEpVsGfj4SMGG6quUK9BRPuTF) 5 | 3. Review the sample code in the \Samples folder 6 | 7 | # What is PowerEvents? 8 | 9 | PowerEvents is a Windows PowerShell module designed to facilitate the ease of creating, updating, and deleting WMI (Windows Management Instrumentation) permanent event registrations. PowerEvents makes it easy to create WMI event filters (define the events you want to capture) and event consumers (responders to events), and then bind them together to initiate the flow of events. By leveraging permanent event registrations, you can perform advanced monitoring functions on a workstation or server, that would otherwise require implementation of an enterprise monitoring product. Because WMI is incredibly vast in the information it provides, very detailed monitoring can be performed using almost any of the WMI objects that exist on a computer. 10 | 11 | # What are WMI Permanent Event Registrations? 12 | 13 | A little-known capability of the WMI service, is its capability to create a permanent registration (listener) for events, and then automatically respond to those events. At a very basic level, it's "if X happens, do Y" but in this case, it's all built into WMI, without the need for any additional software. 14 | 15 | # What Events Can I Monitor with PowerEvents? 16 | 17 | WMI contains a vast amount of information about the Windows operating system, the hardware underneath it, and applications that extend WMI. 18 | 19 | Here are a very few examples of events that you can monitor in WMI: 20 | 21 | - Microsoft Active Directory 22 | - Changes in group policy configuration on GP clients 23 | - Users created or deleted 24 | - Computer accounts moved 25 | - Microsoft System Center Configuration Manager 26 | - Package created, deleted, or modified 27 | - Advertisement created, deleted, or modified 28 | - Collection created, deleted, or modified 29 | - Monitor Disk Events 30 | - USB flash (UFD) or eSATA drive plugged in or removed 31 | - Detect shrink or expansion of partitions 32 | - Monitor Processes 33 | - Start/stop events 34 | - Change in process priority 35 | - Working set (memory utilization) increase/decrease or exceeds "X" value 36 | - I/O operations increase or exceed a certain value 37 | - Windows Services 38 | - Start / stop events 39 | - New service installed or removed 40 | - Service start type changed 41 | - Device changes 42 | - Detect addition or removal of devices 43 | - Print jobs 44 | - Detect new job or finished job 45 | - Changes in job status 46 | - Software & Patches 47 | - Software installed or removed 48 | - New patches installed 49 | - Operating System 50 | - New reliability records created 51 | - New game registered with Windows 7 Games Explorer 52 | - User Events 53 | - User logon / logoff 54 | - Changes to user attributes 55 | - Network 56 | - IP address changed 57 | - Default gateway changed 58 | - Network adapter added or removed 59 | - Server Message Block (SMB) session created or ended 60 | - ODBC Data Sources 61 | - Created or removed 62 | - Driver installed 63 | - Configuration changed 64 | - Threads 65 | - Creation or termination 66 | - Thread state changes 67 | - Microsoft Distributed File System (DFS) 68 | - Last replication time changes 69 | - Errors during replication 70 | - Volume serial # changes 71 | 72 | # Why Should I use PowerEvents? 73 | 74 | Because it's awesome, and it helps you monitor for low-level system events that were previously quite challenging to find! The capabilities of this module are quite vast, only limited by the information available in WMI. Because many applications extend WMI through WMI providers, these can be not just managed, but also extensively monitored. Additionally, the Windows operating system itself makes extensive use of WMI to provide system information to applications. Through this, you can discover and monitor almost anything you'd want to know about your workstation or server! 75 | 76 | - Microsoft Active Directory (AD) 77 | - SQL Server 78 | - Distributed FileSystem (DFS) 79 | - Microsoft DNS 80 | - System Center Configuration Manager (SCCM or ConfigMgr) 81 | - Internet Information Services (IIS) 6 / 7 82 | - Windows XP / Vista / 7 83 | - Windows Server 2003 / 2008 / 2008 R2 84 | 85 | # About the Author 86 | 87 | Twitter: https://twitter.com/pcgeek86 88 | 89 | Website: https://trevorsullivan.net 90 | -------------------------------------------------------------------------------- /Samples/Event Binding - Command Line - Microsoft Outlook Started.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 05/31/11 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding 6 | # that shuts down a computer when Microsoft Outlook is started. 7 | 8 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 9 | New-WmiFilterToConsumerBinding ` 10 | -Consumer (& "${ScriptPath}\Event Consumers\Command Line - Microsoft Outlook Started.ps1") ` 11 | -Filter (& "${ScriptPath}\Event Filters\Event Filter - Microsoft Outlook Started.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Command Line - System Resumed - Restart Windows Service.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 7/9/2011 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding 6 | # that shuts down a computer when Microsoft Outlook is started. 7 | 8 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 9 | New-WmiFilterToConsumerBinding ` 10 | -Consumer (& "${ScriptPath}\Event Consumers\Windows\Command Line - System Resumed - Restart Windows Service.ps1") ` 11 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - System Resumed.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Command Line - User Profile Unloaded - Delete Unused Profiles.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 06/30/11 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that 6 | # removes all unused user profiles upon user logoff. 7 | 8 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 9 | New-WmiFilterToConsumerBinding ` 10 | -Consumer (& "${ScriptPath}\Event Consumers\Command Line - User Profile Unloaded - Delete Unloaded Profiles.ps1") ` 11 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - User Profile Unloaded.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Event Log - Process Creation.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that logs process creations to the Application event log. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Event Log - Process Creation.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - Process Created.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Event Log - Process Termination.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that logs process terminations to the Application event log. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Event Log - Process Termination.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - Process Terminated.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Log File - Print Job Completed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that logs a completed print job to a text file. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Log File - Print Job Completed.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - Print Job Completed.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Log File - Print Job Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that logs a new print job to a text file. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Log File - Print Job Created.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - Print Job Created.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Log File - Process Creation.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 02/22/12 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that logs process creations to a log file. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Log File - Process Created.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - Process Created.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Script - Print Job Completed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that fires a VBscript in response to a completed print job. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Script - Print Job Completed.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - Print Job Completed.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Script - Print Job Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that fires a VBscript in response to a new print job. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Script - Print Job Created.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - Print Job Created.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Script - UFD Installed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/29/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that fires a VBscript in response to a UFD being installed. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Script - UFD Installed.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - UFD Installed.ps1") 11 | -------------------------------------------------------------------------------- /Samples/Event Binding - Script - UFD Removed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/29/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that fires a VBscript in response to a UFD being removed. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Script - UFD Removed.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - UFD Removed.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - ScriptFile - UFD Installed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 12/7/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that executes a VBscript file in response to a UFD being installed. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\ScriptFile - UFD Installed.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - UFD Installed.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - ScriptFile - UFD Removed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/29/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that fires a VBscript in response to a UFD being removed. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\ScriptFile - UFD Removed.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Windows\Event Filter - UFD Removed.ps1") -------------------------------------------------------------------------------- /Samples/Event Binding - Test Command Line VBscript with Process Start Events.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 12/14/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter, consumer, and binding that invokes a VBscript (intended to respond to user profile load events) when a process is started. 6 | 7 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 8 | New-WmiFilterToConsumerBinding ` 9 | -Consumer (& "${ScriptPath}\Event Consumers\Command Line - User Profile Loaded.ps1") ` 10 | -Filter (& "${ScriptPath}\Event Filters\Event Filter - Process Created.ps1") -------------------------------------------------------------------------------- /Samples/Event Consumers/Command Line - Microsoft Outlook Started.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 05/26/11 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that runs a command line in response to Microsoft Outlook being started. 6 | # Note that there are double-quotes explicitly being added around the script path and script arguments (that might have a space in them) 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | $ScriptPath = Split-Path $MyInvocation.MyCommand.Path 11 | New-WmiEventConsumer -Verbose -Name MicrosoftOutlookStarted -ConsumerType CommandLine -CommandLineTemplate "shutdown -r -t 0" 12 | 13 | 14 | <# 15 | MOF of a working example: 16 | 17 | instance of CommandLineEventConsumer 18 | { 19 | CommandLineTemplate = "cscript.exe \"C:\\Users\\Phragcyte\\Documents\\WindowsPowerShell\\Modules\\PowerEvents\\Samples\\Event Consumers\\VBscripts\\User Profile Loaded.vbs\""; 20 | CreateNewConsole = TRUE; 21 | CreateNewProcessGroup = TRUE; 22 | CreatorSID = {1, 5, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0, 7, 96, 247, 25, 179, 246, 87, 123, 169, 67, 178, 173, 232, 3, 0, 0}; 23 | ExecutablePath = "cscript.exe"; 24 | MachineName = NULL; 25 | Name = "UserProfileLoaded"; 26 | WorkingDirectory = NULL; 27 | }; 28 | #> -------------------------------------------------------------------------------- /Samples/Event Consumers/Command Line - User Profile Loaded.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that runs a command line in response to a user profile being loaded. 6 | # Note that there are double-quotes explicitly being added around the script path and script arguments (that might have a space in them) 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | $ScriptPath = Split-Path $MyInvocation.MyCommand.Path 11 | New-WmiEventConsumer -Verbose -Name UserProfileLoaded -ConsumerType CommandLine -CommandLineTemplate "cscript.exe `"${ScriptPath}\VBscripts\User Profile Loaded.vbs`" `"%TargetInstance.Path%`"" 12 | 13 | 14 | <# 15 | MOF of a working example: 16 | 17 | instance of CommandLineEventConsumer 18 | { 19 | CommandLineTemplate = "cscript.exe \"C:\\Users\\Phragcyte\\Documents\\WindowsPowerShell\\Modules\\PowerEvents\\Samples\\Event Consumers\\VBscripts\\User Profile Loaded.vbs\""; 20 | CreateNewConsole = TRUE; 21 | CreateNewProcessGroup = TRUE; 22 | CreatorSID = {1, 5, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0, 7, 96, 247, 25, 179, 246, 87, 123, 169, 67, 178, 173, 232, 3, 0, 0}; 23 | ExecutablePath = "cscript.exe"; 24 | MachineName = NULL; 25 | Name = "UserProfileLoaded"; 26 | WorkingDirectory = NULL; 27 | }; 28 | #> -------------------------------------------------------------------------------- /Samples/Event Consumers/Command Line - User Profile Unloaded - Delete Unloaded Profiles.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that runs a command line in response to a user profile being unloaded. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 7 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventConsumer -Name UserProfileUnloaded-DeleteUnusedProfiles -ConsumerType CommandLine -CommandLineTemplate "powershell.exe -command `"Get-WmiObject -Namespace root\cimv2 -Class Win32_UserProfile -Filter `"Special = 'false' and Loaded = 'false'`" | % { $_.Delete() }`"" -------------------------------------------------------------------------------- /Samples/Event Consumers/Command Line - User Profile Unloaded - Run VBscript.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that runs a command line in response to a user profile being unloaded. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 7 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventConsumer -Name UserProfileUnloaded -ConsumerType CommandLine -CommandLineTemplate "cscript.exe /b c:\temp\resources\UserProfileUnloaded.vbs %TargetInstance.LocalPath%" -------------------------------------------------------------------------------- /Samples/Event Consumers/CommandLine - PowerShellTest.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/29/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a print job completing. 6 | 7 | New-WmiEventConsumer -Name PowerShellTest -ConsumerType CommandLine -ExecutablePath 'c:\windows\system32\powershell.exe' -CommandLineTemplate '-Command { Add-Content -Path }' -------------------------------------------------------------------------------- /Samples/Event Consumers/CommandLine - Script With Args.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/29/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a print job completing. 6 | 7 | New-WmiEventConsumer -Name ScriptWithArgs -ConsumerType CommandLine -ExecutablePath 'c:\windows\system32\cscript.exe' -CommandLineTemplate 'c:\windows\system32\cscript.exe','c:\temp\resources\responder.vbs' -------------------------------------------------------------------------------- /Samples/Event Consumers/ConfigMgr/ConfigMgr - System Resource Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 05/24/11 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to 6 | # a new System Center Configuration Manager system resource being created. 7 | 8 | $VBcode = @" 9 | set fso = CreateObject("Scripting.FileSystemObject") 10 | set LogFile = fso.OpenTextFile("c:\SCCM.log", 8, true) 11 | call LogFile.WriteLine(Date() & " " & Time() & ": New ConfigMgr system resource created!") 12 | "@ 13 | New-WmiEventConsumer -Name ConfigMgrSystemResourceCreated -ConsumerType Script -ScriptText $VBcode -------------------------------------------------------------------------------- /Samples/Event Consumers/Event Log - Process Creation.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/21/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that writes to the event log. 6 | # The InsertionStringTemplates parameter is the message written to the event log. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventConsumer -Name ProcessStarted -ConsumerType EventLog -EventType Information -EventId 9898 ` 11 | -InsertionStringTemplates "Process has started: %TargetInstance.ProcessName%" 12 | 13 | -------------------------------------------------------------------------------- /Samples/Event Consumers/Event Log - Process Termination.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/21/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that writes to the event log. 6 | # The InsertionStringTemplates parameter is the message written to the event log. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventConsumer -Name ProcessStopped -ConsumerType EventLog -EventType Information -EventId 9898 ` 11 | -InsertionStringTemplates 'Process has stopped: %TargetInstance.ProcessName%' 12 | 13 | -------------------------------------------------------------------------------- /Samples/Event Consumers/Log File - Print Job Completed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that writes to a log file. 6 | # The Text parameter is the message written to the event log, using WMI standard string templates. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventConsumer -ConsumerType LogFile -Name PrintJobComplete -FileName $env:windir\temp\PrintJobs.log ` 11 | -Text "Print job has completed. Document is: %TargetInstance.Document%" -------------------------------------------------------------------------------- /Samples/Event Consumers/Log File - Print Job Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that writes to a log file. 6 | # The Text parameter is the message written to the event log, using WMI standard string templates. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventConsumer -ConsumerType LogFile -Name PrintJobCreated -FileName $env:windir\temp\PrintJobs.log ` 11 | -Text "Print job has been created. Document is: %TargetInstance.Document%" -------------------------------------------------------------------------------- /Samples/Event Consumers/Log File - Process Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 02/22/12 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that writes to a log file. 6 | # The Text parameter is the message written to a log file, using WMI standard string templates. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventConsumer -ConsumerType LogFile -Name ProcessCreatedLogFile -FileName $env:windir\temp\Process.log ` 11 | -Text "Process has been created. Process name is: %TargetInstance.Name%" -------------------------------------------------------------------------------- /Samples/Event Consumers/Log File - Process Terminated.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 02/22/12 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that writes to a log file. 6 | # The Text parameter is the message written to a log file, using WMI standard string templates. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventConsumer -ConsumerType LogFile -Name ProcessStoppedLogFile -FileName $env:windir\temp\Process.log ` 11 | -Text "Process has exited. Process name is: %TargetInstance.Name%" -------------------------------------------------------------------------------- /Samples/Event Consumers/Script - Print Job Completed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a print job completing. 6 | 7 | $VBcode = @" 8 | set fso = CreateObject("Scripting.FileSystemObject") 9 | set LogFile = fso.OpenTextFile("c:\Printer.log", 8, true) 10 | call LogFile.WriteLine(Date() & " " & Time() & ": Print job completed") 11 | "@ 12 | New-WmiEventConsumer -Name PrintJobCompleted -ConsumerType Script -ScriptText $VBcode -------------------------------------------------------------------------------- /Samples/Event Consumers/Script - Print Job Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a new print job being created. 6 | 7 | $VBcode = @" 8 | set fso = CreateObject("Scripting.FileSystemObject") 9 | set LogFile = fso.OpenTextFile("c:\Printer.log", 8, true) 10 | call LogFile.WriteLine(Date() & " " & Time() & ": Print job created") 11 | "@ 12 | New-WmiEventConsumer -Name PrintJobCreated -ConsumerType Script -ScriptText $VBcode -------------------------------------------------------------------------------- /Samples/Event Consumers/Script - UFD Installed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a USB flash drive (UFD) being installed. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 7 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 8 | 9 | $VBcode = @" 10 | set fso = CreateObject("Scripting.FileSystemObject") 11 | set LogFile = fso.OpenTextFile("c:\temp\UFDLog.log", 8, true) 12 | call LogFile.WriteLine(Date() & " " & Time() & ": UFD was installed with serial number: " & TargetEvent.TargetInstance.VolumeSerialNumber) 13 | "@ 14 | New-WmiEventConsumer -Name UFDInstalled -ConsumerType Script -ScriptText $VBcode -------------------------------------------------------------------------------- /Samples/Event Consumers/Script - UFD Removed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a USB flash drive (UFD) being removed. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 7 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 8 | 9 | $VBcode = @" 10 | set fso = CreateObject("Scripting.FileSystemObject") 11 | set LogFile = fso.OpenTextFile("c:\temp\UFDLog.log", 8, true) 12 | call LogFile.WriteLine(Date() & " " & Time() & ": UFD was removed") 13 | "@ 14 | New-WmiEventConsumer -Name UFDRemoved -ConsumerType Script -ScriptText $VBcode -------------------------------------------------------------------------------- /Samples/Event Consumers/ScriptFile - UFD Installed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/30/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a USB flash drive (UFD) being removed. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 7 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 8 | 9 | $ScriptPath = Split-Path $MyInvocation.MyCommand.Path 10 | New-WmiEventConsumer -Name ScriptFileUFDInstalled -ConsumerType Script -ScriptFile "$ScriptPath\VBscripts\UFD Installed.vbs" -------------------------------------------------------------------------------- /Samples/Event Consumers/ScriptFile - UFD Removed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/30/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that calls a script in response to a USB flash drive (UFD) being removed. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 7 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventConsumer -Name ScriptFileUFDRemoved -ConsumerType Script -ScriptFile 'c:\temp\resources\Responder.vbs' -------------------------------------------------------------------------------- /Samples/Event Consumers/VBscripts/UFD Installed.vbs: -------------------------------------------------------------------------------- 1 | 'On Error Resume Next 2 | set fso = CreateObject("Scripting.FileSystemObject") 3 | ' Open a text file. 8 = ForAppending; True = Create file if non-existent 4 | set LogFile = fso.OpenTextFile("UFD Installed.log", 8, true) 5 | call LogFile.WriteLine("UFD Installed") 6 | call LogFile.WriteLine("UFD installed with serial number: " & TargetEvent.TargetInstance.VolumeSerialNumber) -------------------------------------------------------------------------------- /Samples/Event Consumers/VBscripts/User Profile Loaded.vbs: -------------------------------------------------------------------------------- 1 | set fso = CreateObject("Scripting.FileSystemObject") 2 | set LogFile = fso.OpenTextFile("c:\temp\User Profile Loaded.log", 8, true) 3 | call LogFile.WriteLine(Date() & " " & Time() & ": User profile loaded script has begun") 4 | ' call LogFile.WriteLine(TargetEvent.TargetInstance.LocalPath) 5 | 6 | 7 | ' Option Explicit 8 | dim fso, LogFile 9 | 10 | ' If TargetEvent is not defined, then we are not running the script from the ActiveScriptEventConsumer 11 | 'if wscript then 12 | ' ScriptConsumer = false 13 | 'end if 14 | -------------------------------------------------------------------------------- /Samples/Event Consumers/Windows/Command Line - System Resumed - Restart Windows Service.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event consumer that runs a command line in response to a user profile being loaded. 6 | # Note that there are double-quotes explicitly being added around the script path and script arguments (that might have a space in them) 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event consumer. 8 | # A fully functioning sample requires an event filter, to define the events, as well as a binding between the filter and consumer. 9 | 10 | $RestartScript = @' 11 | $ServiceName = $args[0] 12 | Add-Content -Path 'c:\Restart Service.log' -Value "Service name is: $ServiceName" 13 | $Service = @(Get-WmiObject -Namespace root\cimv2 -Class Win32_Service -Filter "Name = '$ServiceName'") 14 | Add-Content -Path 'C:\Restart Service.log' -Value "Found $($Service.Count) instances of '$ServiceName' service" 15 | $Result = $Service[0].StopService() 16 | Add-Content -Path 'c:\Restart Service.log' -Value "Stopped service with result: $($Result.ReturnValue)" 17 | Start-Sleep 4 18 | $Result = $Service[0].StartService() 19 | Add-Content -Path 'c:\Restart Service.log' -Value "Started service with result: $($Result.ReturnValue)" 20 | Add-Content -Path 'c:\Restart Service.log' -Value "Exiting restart service script" 21 | '@ 22 | Remove-Item -Force -Path "$($env:WinDir)\temp\Restart Windows Service.ps1" 23 | Add-Content -Path "$($env:WinDir)\temp\Restart Windows Service.ps1" -Value $RestartScript 24 | 25 | $ScriptPath = Split-Path $MyInvocation.MyCommand.Path 26 | New-WmiEventConsumer -Verbose -Name SystemResumedRestartService -ConsumerType CommandLine -CommandLineTemplate "powershell.exe -command `". '$($env:WinDir)\temp\Restart Windows Service.ps1' 'PS3 Media Server'`"" 27 | 28 | 29 | <# 30 | MOF of a working command line consumer example: 31 | 32 | instance of CommandLineEventConsumer 33 | { 34 | CommandLineTemplate = "cscript.exe \"C:\\Users\\Phragcyte\\Documents\\WindowsPowerShell\\Modules\\PowerEvents\\Samples\\Event Consumers\\VBscripts\\User Profile Loaded.vbs\""; 35 | CreateNewConsole = TRUE; 36 | CreateNewProcessGroup = TRUE; 37 | CreatorSID = {1, 5, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0, 7, 96, 247, 25, 179, 246, 87, 123, 169, 67, 178, 173, 232, 3, 0, 0}; 38 | ExecutablePath = "cscript.exe"; 39 | MachineName = NULL; 40 | Name = "UserProfileLoaded"; 41 | WorkingDirectory = NULL; 42 | }; 43 | #> -------------------------------------------------------------------------------- /Samples/Event Consumers/Windows/Support/Restart Windows Service.ps1: -------------------------------------------------------------------------------- 1 | $ServiceName = 'PS3 Media Server' 2 | $Service = Get-WmiObject -Namespace root\cimv2 -Class Win32_Service -Filter "Name = '$Service'" 3 | $Service.StopService() 4 | $Service.StartService() -------------------------------------------------------------------------------- /Samples/Event Filters/Active Directory/Event Filter - Active Directory - Computer Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a computer object in Active Directory (AD). 6 | # Take note that, if a computer account is moved, the WMI instance that represents the computer will be deleted and a new one created. A modification event (__InstanceModificationEvent) will NOT be fired in this scenario. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -EventNamespace root\directory\ldap -Name ADComputerCreated ` 11 | -Query "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'ds_computer'" -------------------------------------------------------------------------------- /Samples/Event Filters/Active Directory/Event Filter - Active Directory - Computer Deleted.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the deletion of a computer object in Active Directory (AD). 6 | # Take note that, if a computer account is moved, the WMI instance that represents the computer will be deleted and a new one created. A modification event (__InstanceModificationEvent) will NOT be fired in this scenario. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -EventNamespace root\directory\ldap -Name ADComputerCreated ` 11 | -Query "select * from __InstanceDeletionEvent within 5 where TargetInstance ISA 'ds_computer'" -------------------------------------------------------------------------------- /Samples/Event Filters/Active Directory/Event Filter - Active Directory - User Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a user object in Active Directory (AD). 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -EventNamespace root\directory\ldap -Name ADUserCreated ` 10 | -Query "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'ds_user'" -------------------------------------------------------------------------------- /Samples/Event Filters/Active Directory/Event Filter - Active Directory - User Deleted.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the deletion of a user object in Active Directory (AD). 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -EventNamespace root\directory\ldap -Name ADUserDeleted ` 10 | -Query "select * from __InstanceDeletionEvent within 5 where TargetInstance ISA 'ds_user'" -------------------------------------------------------------------------------- /Samples/Event Filters/Clustering/Event Filter - Cluster State Changed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 12/1/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when a Microsoft cluster resource state changes for any reason. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name ClusterStateChanged -Query "select * from __InstanceModificationEvent within 5 where TargetInstance ISA 'MSCluster_Resource' and TargetInstance.State <> PreviousInstance.State" -------------------------------------------------------------------------------- /Samples/Event Filters/Clustering/Event Filter - Cluster State Offline.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 12/1/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when a Microsoft cluster resource goes offline. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name ClusterStateOffline -Query "select * from __InstanceModificationEvent within 5 where TargetInstance ISA 'MSCluster_Resource' and TargetInstance.State <> PreviousInstance.State and TargetInstance.State = 3" -------------------------------------------------------------------------------- /Samples/Event Filters/Clustering/Event Filter - Cluster State Online.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 12/1/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when a Microsoft cluster resource comes online. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name ClusterStateOnline -Query "select * from __InstanceModificationEvent within 5 where TargetInstance ISA 'MSCluster_Resource' and TargetInstance.State <> PreviousInstance.State and TargetInstance.State = 3" -------------------------------------------------------------------------------- /Samples/Event Filters/ConfigMgr/Event Filter - ConfigMgr - Advertisement Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a new System Center Configuration Mananger (ConfigMgr) advertisement. 6 | # This example assumes that the ConfigMgr site code is 'LAB' and the script is being executed on the primary site server. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ConfigMgrAdvertisementCreated -EventNamespace root\sms\site_lab -Query "select * from __InstanceCreationEvent within 2 where TargetInstance ISA 'SMS_Advertisement'" -------------------------------------------------------------------------------- /Samples/Event Filters/ConfigMgr/Event Filter - ConfigMgr - Advertisement Deleted.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the deletion of a System Center Configuration Mananger (ConfigMgr) advertisement. 6 | # This example assumes that the ConfigMgr site code is 'LAB' and the script is being executed on the primary site server. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ConfigMgrAdvertisementDeleted -EventNamespace root\sms\site_lab -Query "select * from __InstanceDeletionEvent within 2 where TargetInstance ISA 'SMS_Advertisement'" -------------------------------------------------------------------------------- /Samples/Event Filters/ConfigMgr/Event Filter - ConfigMgr - Collection Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a new System Center Configuration Mananger (ConfigMgr) collection. 6 | # This example assumes that the ConfigMgr site code is 'LAB' and the script is being executed on the primary site server. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ConfigMgrCollectionCreated -EventNamespace root\sms\site_lab -Query "select * from __InstanceCreationEvent within 2 where TargetInstance ISA 'SMS_Collection'" -------------------------------------------------------------------------------- /Samples/Event Filters/ConfigMgr/Event Filter - ConfigMgr - Collection Deleted.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the deletion of a System Center Configuration Mananger (ConfigMgr) collection. 6 | # This example assumes that the ConfigMgr site code is 'LAB' and the script is being executed on the primary site server. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ConfigMgrCollectionDeleted -EventNamespace root\sms\site_lab -Query "select * from __InstanceDeletionEvent within 2 where TargetInstance ISA 'SMS_Collection'" -------------------------------------------------------------------------------- /Samples/Event Filters/ConfigMgr/Event Filter - ConfigMgr - Package Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a new System Center Configuration Mananger (ConfigMgr) package. 6 | # This example assumes that the ConfigMgr site code is 'LAB' and the script is being executed on the primary site server. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ConfigMgrPackageCreated -EventNamespace root\sms\site_lab -Query "select * from __InstanceCreationEvent within 2 where TargetInstance ISA 'SMS_Package'" -------------------------------------------------------------------------------- /Samples/Event Filters/ConfigMgr/Event Filter - ConfigMgr - Package Deleted.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the deletion of a System Center Configuration Mananger (ConfigMgr) package. 6 | # This example assumes that the ConfigMgr site code is 'LAB' and the script is being executed on the primary site server. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ConfigMgrPackageDeleted -EventNamespace root\sms\site_lab -Query "select * from __InstanceDeletionEvent within 2 where TargetInstance ISA 'SMS_Package'" -------------------------------------------------------------------------------- /Samples/Event Filters/ConfigMgr/Event Filter - ConfigMgr - Resource Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 05/24/11 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a new System Center Configuration Mananger (ConfigMgr) system resource. 6 | # This example assumes that the ConfigMgr site code is 'LAB' and the script is being executed on the primary site server. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ConfigMgrSystemResourceCreated -EventNamespace root\sms\site_lab -Query "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'SMS_R_System'" -------------------------------------------------------------------------------- /Samples/Event Filters/Event Filter - Microsoft Outlook Started.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 05/25/11 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when Microsoft Outlook is started. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name MicrosoftOutlookStarted -Query "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_Process' and TargetInstance.Name = 'outlook.exe'" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - IP Address Changed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 02/08/14 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when the IP address changes 6 | # on any installed network interface on a Windows operating system. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name IPAddressChanged -Query "select * from __InstanceModificationEvent within 30 where TargetInstance ISA 'Win32_NetworkAdapterConfiguration' and TargetInstance.IPAddress <> PreviousInstance.IPAddress"; -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - Print Job Completed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the deletion of a print job. 6 | # If a print job is deleted, it mostly likely indicates that the job has completed, or been canceled. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name PrintJobDeleted -Query "select * from __InstanceDeletionEvent within 2 where TargetInstance ISA 'Win32_PrintJob'" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - Print Job Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a new print job. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name PrintJobCreated -Query "select * from __InstanceCreationEvent within 2 where TargetInstance ISA 'Win32_PrintJob'" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - Process Created.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the creation of a Windows process. 6 | # Processes are started and stopped constantly, in particular depending on user activity. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ProcessStarted -Query "select * from __InstanceCreationEvent within 2 where TargetInstance ISA 'Win32_Process'" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - Process Terminated.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/22/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects the termination of a Windows process. 6 | # Processes are started and stopped constantly, in particular depending on user activity. 7 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 8 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 9 | 10 | New-WmiEventFilter -Name ProcessTerminated -Query "select * from __InstanceDeletionEvent within 2 where TargetInstance ISA 'Win32_Process'" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - System Resumed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 7/9/2011 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when the system has been resumed. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name SystemResumed -Query "select * from Win32_PowerManagementEvent where EventType = 7" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - UFD Installed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when a USB flash drive is installed. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name SystemResumed -Query "select * from __InstanceCreationEvent within 2 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - UFD Removed.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/29/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when a USB flash drive is removed. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name UFDRemoved -Query "select * from __InstanceDeletionEvent within 2 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - User Profile Loaded.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/28/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when a user profile is loaded. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name UserProfileLoaded -Query "select * from __InstanceModificationEvent within 2 where TargetInstance ISA 'Win32_UserProfile' and TargetInstance.Loaded <> PreviousInstance.Loaded and TargetInstance.Loaded = TRUE" -------------------------------------------------------------------------------- /Samples/Event Filters/Windows/Event Filter - User Profile Unloaded.ps1: -------------------------------------------------------------------------------- 1 | # EXAMPLE for PowerEvents PowerShell module available on http://powerevents.codeplex.com 2 | # 3 | # Author: Trevor Sullivan 4 | # Date: 11/29/10 5 | # Brief: This example shows how to use PowerEvents to create a WMI event filter that detects when a user profile is unloaded. 6 | # Note: This is not a complete working sample of the PowerEvents module. This only shows how to create an event filter. 7 | # A fully functioning sample requires an event consumer, to respond to the events, as well as a binding between the filter and consumer. 8 | 9 | New-WmiEventFilter -Name UserProfileLoaded -Query "select * from __InstanceModificationEvent within 2 where TargetInstance ISA 'Win32_UserProfile' and TargetInstance.Loaded <> PreviousInstance.Loaded and TargetInstance.Loaded = FALSE" -------------------------------------------------------------------------------- /Samples/README.txt: -------------------------------------------------------------------------------- 1 | IMPORTANT: Not all of the examples in this folder have been tested for functionality. Use the samples at your own risk! 2 | 3 | Event filter examples exist in 'PowerEvents\Samples\Event Filters' 4 | Event consumer examples exist in 'PowerEvents\Samples\Event Consumers' 5 | 6 | Event bindings exist in the root of the samples folder. This makes it easier to references filters and consumers. 7 | The event binding scripts make use of the filter and consumer scripts, and together, are complete examples. -------------------------------------------------------------------------------- /Samples/Test-PowerEvents.ps1: -------------------------------------------------------------------------------- 1 | # Test WMI Query: select * from __InstanceOperationsEvent where TargetInstance ISA 'Win32_Process' 2 | 3 | Clear-Host 4 | 5 | # Enable verbose messages to be written to console output 6 | $VerbosePreference = 'Continue' 7 | $DebugPreference = 'Continue' 8 | 9 | #region Get script path 10 | #$MyInvocation.MyCommand.Path 11 | ${ScriptPath} = Split-Path $MyInvocation.MyCommand.Path 12 | # Write-Verbose -Message "Script path is: ${ScriptPath}" 13 | #endregion 14 | 15 | #region Import WMI Event Management module 16 | if (-not (Get-Module 'WMI Event Management')) 17 | { 18 | Remove-Module -Name 'WMI Event Management' 19 | } 20 | else 21 | { 22 | Import-Module -Name 'WMI Event Management' 23 | } 24 | #endregion Import WMI Event Management module 25 | 26 | #region Create VBscript responder for ActiveScriptEventConsumer 27 | # All this VBscript does is log some text to "c:\temp\vboutput.log" 28 | 29 | $VBResponderText = @" 30 | Option Explicit 31 | dim fso, logfile, logpath, sh 32 | set sh = CreateObject("Wscript.Shell") 33 | '*** Log an event to the application event log 34 | call sh.LogEvent(0, "Script executed at: " & Time()) 35 | logpath = "c:\temp\vboutput.log" 36 | set fso = CreateObject("Scripting.FileSystemObject") 37 | 'if fso.FileExists(logpath) then call fso.DeleteFile(logpath, true) 38 | set logfile = fso.OpenTextFile(logpath, 8, true) 39 | call logfile.WriteLine(Date() & Time()) 40 | '*** Release object handles 41 | set fso = nothing 42 | set logfile = nothing 43 | "@ 44 | # Create VBscript responder file (aka. event handler script) 45 | [void] (New-Item -ItemType Directory -Path c:\temp -Force) 46 | [void] (New-Item -ItemType Directory -Path c:\temp\resources -Force) 47 | [void] (New-Item -ItemType File -Path c:\temp\resources\Responder.vbs -Force) 48 | Remove-Item -Path 'c:\temp\Resources\Responder.vbs' 49 | Set-Content -Path 'c:\temp\Resources\Responder.vbs' -Value $VBResponderText -Force 50 | #endregion 51 | 52 | #region Clean up WMI stuff 53 | <# 54 | Get-WmiObject ActiveScriptEventConsumer -Namespace root\default | Remove-WmiObject 55 | Get-WmiObject CommandLineEventConsumer -Namespace root\default | Remove-WmiObject 56 | Get-WmiObject ActiveScriptEventConsumer -Namespace root\subscription | Remove-WmiObject 57 | Get-WmiObject CommandLineEventConsumer -Namespace root\subscription | Remove-WmiObject 58 | Get-WmiObject __EventFilter -Namespace root\default | Remove-WmiObject 59 | Get-WmiObject __EventFilter -Namespace root\cimv2 | Remove-WmiObject 60 | Get-WmiObject __FilterToConsumerBinding -Namespace root\default | Remove-WmiObject 61 | Get-WmiObject __FilterToConsumerBinding -Namespace root\cimv2 | Remove-WmiObject 62 | #> 63 | #endregion 64 | 65 | #region Perform event monitoring for WMI event consumers 66 | <# 67 | Get-EventSubscriber | Unregister-Event 68 | Register-WmiEvent -Namespace root\cimv2 -Class __EventDroppedEvent -Action { Write-Host "Event dropped in root\cimv2" } 69 | Register-WmiEvent -Namespace root\cimv2 -Class __EventQueueOverflowEvent -Action { Write-Host "Event dropped in root\cimv2" } 70 | Register-WmiEvent -Namespace root\default -Class __EventDroppedEvent -Action { Write-Host "Event dropped in root\cimv2" } 71 | Register-WmiEvent -Namespace root\default -Class __EventQueueOverflowEvent -Action { Write-Host "Event dropped in root\cimv2" } 72 | Register-WmiEvent -Namespace root\subscription -Class __ConsumerFailureEvent -Action { Write-Host "Consumer failed" } 73 | #> 74 | #endregion 75 | 76 | #region Test creation of event consumer 77 | # TEST: Create script consumer with both ${ScriptFile} and ${ScriptText} defined (should not work) 78 | # RESULT (11.02.10): Added some parameter validation code that ensures validation will fail if both parameters ${ScriptFile} and ${ScriptText} are defined. 79 | $ScriptConsumer = New-WmiEventConsumer -Consumer Script -ScriptFile 'c:\temp\Resources\Responder.vbs' -ScriptText 'set fso = CreateObject("Scripting.FileSystemObject")' -Name TestConsumer 80 | 81 | # TEST: Create script consumer from script text 82 | # RESULT (11.02.10): Works as expected, but did not validate that it responds correctly when bound to an event filter 83 | $ScriptConsumer = New-WmiEventConsumer -Consumer Script -ScriptText $VBResponderText -Name TestConsumer 84 | 85 | # TEST: Create script consumer with neither ${ScriptFile} or ${ScriptText} defined 86 | # RESULT (11.02.10): Fails with "parameter set cannot be resolved" 87 | $ScriptConsumer = New-WmiEventConsumer -Consumer Script -ScriptingEngine VBscript -Name TestConsumer 88 | 89 | # TEST: Create script consumer from script file 90 | $ScriptConsumer = New-WmiEventConsumer -Consumer Script -ScriptFile 'c:\temp\Resources\Responder.vbs' -Name TestConsumer 91 | 92 | # Create SMTP consumer 93 | $SmtpConsumer = New-WmiEventConsumer -ConsumerType SMTP -Name TestConsumer -SMTPServer 'localhost' -FromLine 'notifications@test.loc' -Subject 'WMI Notification' -Message '%TargetInstance.Name%' -ToLine 'trevor@test.loc' 94 | # Create log file event consumer 95 | $LogFileConsumer = New-WmiEventConsumer -ConsumerType LogFile -Name TestConsumer -Text 'Process started: %TargetInstance.Name% at %TIME_CREATED%' -FileName c:\temp\LogFileOutput.log 96 | # Create command line consumer 97 | $CliConsumer = New-WmiEventConsumer -ConsumerType 'CommandLine' -Name TestConsumer -ExecutablePath 'cmd.exe /c ipconfig >> c:\temp\clioutput.log' 98 | # Create NT Event Log consumer 99 | $EventLogConsumer = New-WmiEventConsumer -ConsumerType EventLog -Name TestConsumer -InsertionStringTemplates 'New instance created: %TargetInstance.__PATH%' -EventId 10 -EventType Information -Category 10 -UNCServerName localhost 100 | #endregion Test creation of event consumer 101 | 102 | #region Test creation of event filter 103 | # Test filter creation with computer name 104 | $Filter = New-WmiEventFilter -ComputerName 'gaming' -Name TestFilter -EventNamespace root\cimv2 -Query "select * from __InstanceCreationEvent WITHIN 5 where TargetInstance ISA 'Win32_Process'" 105 | 106 | # Test filter creation without computer name 107 | $Filter = New-WmiEventFilter -Name TestFilter -EventNamespace root\cimv2 -Query "select * from __InstanceCreationEvent WITHIN 5 where TargetInstance ISA 'Win32_Process'" 108 | #endregion Test creation of event filter 109 | 110 | #region Test creation of Filter-To-Consumer bindings 111 | # New-WmiFilterToConsumerBinding -Consumer $CliConsumer -Filter $Filter 112 | # New-WmiFilterToConsumerBinding -Consumer $ScriptConsumer -Filter $Filter 113 | # New-WmiFilterToConsumerBinding -Consumer $SmtpConsumer -Filter $Filter 114 | New-WmiFilterToConsumerBinding -Consumer $LogFileConsumer -Filter $Filter 115 | #endregion Test creation of Filter-To-Consumer bindings 116 | 117 | exit # Comment this line to enable clean up 118 | 119 | # **************** RUN THIS SECTION OF THE SCRIPT TO CLEAN UP WMI EVENT INSTANCES **************** 120 | # **************** RUN THIS SECTION OF THE SCRIPT TO CLEAN UP WMI EVENT INSTANCES **************** 121 | # **************** RUN THIS SECTION OF THE SCRIPT TO CLEAN UP WMI EVENT INSTANCES **************** 122 | 123 | # Clean up consumer instances 124 | Remove-WmiObject -Path "root\subscription:ActiveScriptEventConsumer.Name='TestConsumer'" 125 | Remove-WmiObject -Path "root\subscription:SMTPEventConsumer.Name='TestConsumer'" 126 | Remove-WmiObject -Path "root\subscription:LogFileEventConsumer.Name='TestConsumer'" 127 | Remove-WmiObject -Path "root\subscription:NTEventLogEventConsumer.Name='TestConsumer'" 128 | Remove-WmiObject -Path "root\subscription:CommandLineEventConsumer.Name='TestConsumer'" 129 | 130 | # Clean up __EventFilter instances 131 | Get-WmiObject -Namespace root\subscription -Query "select * from __EventFilter where Name like '%Test%'" | Remove-WmiObject 132 | 133 | # Clean up test bindings 134 | Get-WmiObject -Namespace root\subscription -Class __FilterToConsumerBinding | ? { $_.Consumer -like '*TestConsumer*' } | Remove-WmiObject -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WmiEventHelper", "WmiEventHelper\WmiEventHelper.csproj", "{6D02E948-C6AB-4444-B19E-E48DD9D83F14}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|x86 = Debug|x86 9 | Release|x86 = Release|x86 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {6D02E948-C6AB-4444-B19E-E48DD9D83F14}.Debug|x86.ActiveCfg = Debug|x86 13 | {6D02E948-C6AB-4444-B19E-E48DD9D83F14}.Debug|x86.Build.0 = Debug|x86 14 | {6D02E948-C6AB-4444-B19E-E48DD9D83F14}.Release|x86.ActiveCfg = Release|x86 15 | {6D02E948-C6AB-4444-B19E-E48DD9D83F14}.Release|x86.Build.0 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Form1.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace WmiEventHelper 2 | { 3 | partial class FormWmiEventHelper 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.ListFilters = new System.Windows.Forms.ListView(); 32 | this.ListConsumers = new System.Windows.Forms.ListView(); 33 | this.label1 = new System.Windows.Forms.Label(); 34 | this.ComboConsumerType = new System.Windows.Forms.ComboBox(); 35 | this.label2 = new System.Windows.Forms.Label(); 36 | this.label3 = new System.Windows.Forms.Label(); 37 | this.BtnRemoveFilter = new System.Windows.Forms.Button(); 38 | this.BtnRemoveConsumer = new System.Windows.Forms.Button(); 39 | this.label4 = new System.Windows.Forms.Label(); 40 | this.ListBoxBindings = new System.Windows.Forms.ListBox(); 41 | this.ButtonRemoveBinding = new System.Windows.Forms.Button(); 42 | this.SuspendLayout(); 43 | // 44 | // ListFilters 45 | // 46 | this.ListFilters.Location = new System.Drawing.Point(12, 29); 47 | this.ListFilters.Name = "ListFilters"; 48 | this.ListFilters.Size = new System.Drawing.Size(253, 227); 49 | this.ListFilters.TabIndex = 0; 50 | this.ListFilters.UseCompatibleStateImageBehavior = false; 51 | this.ListFilters.View = System.Windows.Forms.View.List; 52 | // 53 | // ListConsumers 54 | // 55 | this.ListConsumers.Location = new System.Drawing.Point(274, 71); 56 | this.ListConsumers.Name = "ListConsumers"; 57 | this.ListConsumers.Size = new System.Drawing.Size(256, 185); 58 | this.ListConsumers.TabIndex = 3; 59 | this.ListConsumers.UseCompatibleStateImageBehavior = false; 60 | this.ListConsumers.View = System.Windows.Forms.View.List; 61 | // 62 | // label1 63 | // 64 | this.label1.AutoSize = true; 65 | this.label1.Location = new System.Drawing.Point(271, 55); 66 | this.label1.Name = "label1"; 67 | this.label1.Size = new System.Drawing.Size(59, 13); 68 | this.label1.TabIndex = 2; 69 | this.label1.Text = "Consumers"; 70 | // 71 | // ComboConsumerType 72 | // 73 | this.ComboConsumerType.FormattingEnabled = true; 74 | this.ComboConsumerType.Items.AddRange(new object[] { 75 | "ActiveScriptEventConsumer", 76 | "SMTPEventConsumer", 77 | "LogFileEventConsumer", 78 | "NTEventLogEventConsumer", 79 | "CommandLineEventConsumer"}); 80 | this.ComboConsumerType.Location = new System.Drawing.Point(274, 31); 81 | this.ComboConsumerType.Name = "ComboConsumerType"; 82 | this.ComboConsumerType.Size = new System.Drawing.Size(256, 21); 83 | this.ComboConsumerType.TabIndex = 2; 84 | this.ComboConsumerType.SelectedIndexChanged += new System.EventHandler(this.ComboConsumerType_SelectedIndexChanged); 85 | // 86 | // label2 87 | // 88 | this.label2.AutoSize = true; 89 | this.label2.Location = new System.Drawing.Point(271, 13); 90 | this.label2.Name = "label2"; 91 | this.label2.Size = new System.Drawing.Size(81, 13); 92 | this.label2.TabIndex = 4; 93 | this.label2.Text = "Consumer Type"; 94 | // 95 | // label3 96 | // 97 | this.label3.AutoSize = true; 98 | this.label3.Location = new System.Drawing.Point(9, 9); 99 | this.label3.Name = "label3"; 100 | this.label3.Size = new System.Drawing.Size(34, 13); 101 | this.label3.TabIndex = 5; 102 | this.label3.Text = "Filters"; 103 | // 104 | // BtnRemoveFilter 105 | // 106 | this.BtnRemoveFilter.Location = new System.Drawing.Point(66, 263); 107 | this.BtnRemoveFilter.Name = "BtnRemoveFilter"; 108 | this.BtnRemoveFilter.Size = new System.Drawing.Size(145, 23); 109 | this.BtnRemoveFilter.TabIndex = 1; 110 | this.BtnRemoveFilter.Text = "Remove Filter"; 111 | this.BtnRemoveFilter.UseVisualStyleBackColor = true; 112 | this.BtnRemoveFilter.Click += new System.EventHandler(this.BtnRemoveFilter_Click); 113 | // 114 | // BtnRemoveConsumer 115 | // 116 | this.BtnRemoveConsumer.Location = new System.Drawing.Point(334, 262); 117 | this.BtnRemoveConsumer.Name = "BtnRemoveConsumer"; 118 | this.BtnRemoveConsumer.Size = new System.Drawing.Size(136, 23); 119 | this.BtnRemoveConsumer.TabIndex = 4; 120 | this.BtnRemoveConsumer.Text = "Remove Consumer"; 121 | this.BtnRemoveConsumer.UseVisualStyleBackColor = true; 122 | this.BtnRemoveConsumer.Click += new System.EventHandler(this.BtnRemoveConsumer_Click); 123 | // 124 | // label4 125 | // 126 | this.label4.AutoSize = true; 127 | this.label4.Location = new System.Drawing.Point(533, 13); 128 | this.label4.Name = "label4"; 129 | this.label4.Size = new System.Drawing.Size(47, 13); 130 | this.label4.TabIndex = 7; 131 | this.label4.Text = "Bindings"; 132 | // 133 | // ListBoxBindings 134 | // 135 | this.ListBoxBindings.FormattingEnabled = true; 136 | this.ListBoxBindings.HorizontalScrollbar = true; 137 | this.ListBoxBindings.Location = new System.Drawing.Point(536, 31); 138 | this.ListBoxBindings.Name = "ListBoxBindings"; 139 | this.ListBoxBindings.Size = new System.Drawing.Size(250, 225); 140 | this.ListBoxBindings.TabIndex = 8; 141 | // 142 | // ButtonRemoveBinding 143 | // 144 | this.ButtonRemoveBinding.Location = new System.Drawing.Point(599, 262); 145 | this.ButtonRemoveBinding.Name = "ButtonRemoveBinding"; 146 | this.ButtonRemoveBinding.Size = new System.Drawing.Size(125, 23); 147 | this.ButtonRemoveBinding.TabIndex = 9; 148 | this.ButtonRemoveBinding.Text = "Remove Binding"; 149 | this.ButtonRemoveBinding.UseVisualStyleBackColor = true; 150 | this.ButtonRemoveBinding.Click += new System.EventHandler(this.ButtonRemoveBinding_Click); 151 | // 152 | // FormWmiEventHelper 153 | // 154 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 155 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 156 | this.ClientSize = new System.Drawing.Size(798, 296); 157 | this.Controls.Add(this.ButtonRemoveBinding); 158 | this.Controls.Add(this.ListBoxBindings); 159 | this.Controls.Add(this.label4); 160 | this.Controls.Add(this.BtnRemoveConsumer); 161 | this.Controls.Add(this.BtnRemoveFilter); 162 | this.Controls.Add(this.label3); 163 | this.Controls.Add(this.label2); 164 | this.Controls.Add(this.ComboConsumerType); 165 | this.Controls.Add(this.label1); 166 | this.Controls.Add(this.ListConsumers); 167 | this.Controls.Add(this.ListFilters); 168 | this.Name = "FormWmiEventHelper"; 169 | this.Text = "WMI Event Helper"; 170 | this.ResumeLayout(false); 171 | this.PerformLayout(); 172 | 173 | } 174 | 175 | #endregion 176 | 177 | private System.Windows.Forms.ListView ListFilters; 178 | private System.Windows.Forms.ListView ListConsumers; 179 | private System.Windows.Forms.Label label1; 180 | private System.Windows.Forms.ComboBox ComboConsumerType; 181 | private System.Windows.Forms.Label label2; 182 | private System.Windows.Forms.Label label3; 183 | private System.Windows.Forms.Button BtnRemoveFilter; 184 | private System.Windows.Forms.Button BtnRemoveConsumer; 185 | private System.Windows.Forms.Label label4; 186 | private System.Windows.Forms.ListBox ListBoxBindings; 187 | private System.Windows.Forms.Button ButtonRemoveBinding; 188 | } 189 | } 190 | 191 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Form1.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Trevor Sullivan 3 | * 4 | * Date: 12/14/10 5 | * 6 | * Purpose: This program helps to delete WMI event consumers and filters 7 | * 8 | */ 9 | using System; 10 | using System.Collections.Generic; 11 | using System.ComponentModel; 12 | using System.Data; 13 | using System.Drawing; 14 | using System.Diagnostics; 15 | using System.Text; 16 | using System.Windows.Forms; 17 | using System.Management; 18 | 19 | namespace WmiEventHelper 20 | { 21 | public partial class FormWmiEventHelper : Form 22 | { 23 | public FormWmiEventHelper() 24 | { 25 | InitializeComponent(); 26 | 27 | PopulateFilters(); 28 | PopulateBindings(); 29 | } 30 | 31 | private void PopulateConsumers(string ConsumerType) 32 | { 33 | // Clear all items from consumer ListBox 34 | ListConsumers.Items.Clear(); 35 | 36 | try 37 | { 38 | ManagementClass consumerclass = new ManagementClass(@"root\subscription:" + ConsumerType); 39 | ManagementObjectCollection consumerlist = consumerclass.GetInstances(); 40 | ListViewGroup ligroup = new ListViewGroup("Consumers", HorizontalAlignment.Left); 41 | 42 | foreach (ManagementObject consumer in consumerlist) 43 | { 44 | ListViewItem li = new ListViewItem(consumer.Properties["Name"].Value.ToString(), ligroup); 45 | Debug.WriteLine("Consumer name: " + consumer.Properties["Name"].Value.ToString()); 46 | ListConsumers.Items.Add(li); 47 | } 48 | } 49 | catch 50 | { 51 | Debug.WriteLine("Error occurred enumerating consumers of type: " + ConsumerType); 52 | } 53 | } 54 | 55 | private void PopulateFilters() 56 | { 57 | ListFilters.Items.Clear(); 58 | 59 | ManagementClass filters = new ManagementClass(@"root\subscription:__EventFilter"); 60 | ManagementObjectCollection filterlist = filters.GetInstances(); 61 | ListViewGroup ligroup = new ListViewGroup("Filters",HorizontalAlignment.Left); 62 | 63 | foreach (ManagementObject filter in filterlist) 64 | { 65 | ListViewItem li = new ListViewItem(filter.Properties["Name"].Value.ToString()); 66 | Debug.WriteLine("Filter name: " + filter.Properties["Name"].Value.ToString()); 67 | ListFilters.Items.Add(li); 68 | } 69 | 70 | } 71 | 72 | private void PopulateBindings() 73 | { 74 | ListBoxBindings.Items.Clear(); 75 | 76 | ManagementClass bindingclass = new ManagementClass(@"root\subscription:__FilterToConsumerBinding"); 77 | ManagementObjectCollection bindinglist = bindingclass.GetInstances(); 78 | 79 | foreach (ManagementObject binding in bindinglist) 80 | { 81 | ListBoxBindings.Items.Add(binding.Path.ToString()); 82 | Debug.WriteLine("Binding path is: " + binding.Path.ToString()); 83 | } 84 | } 85 | 86 | private bool RemoveFilter(string name) 87 | { 88 | try 89 | { 90 | ManagementObject filter = new ManagementObject(@"root\subscription:__EventFilter.Name='" + name + "'"); 91 | filter.Delete(); 92 | Debug.WriteLine("Successfully deleted WMI event filter: " + name); 93 | return true; 94 | } 95 | catch 96 | { 97 | Debug.WriteLine("Error occurred deleting filter with name: " + name); 98 | } 99 | return false; 100 | } 101 | 102 | private bool RemoveConsumer(string name, string ConsumerClass) 103 | { 104 | try 105 | { 106 | ManagementObject consumer = new ManagementObject(@"root\subscription:" + ConsumerClass + ".Name='" + name + "'"); 107 | consumer.Delete(); 108 | Debug.WriteLine("Successfully deleted WMI event consumer type (" + ConsumerClass + ") named: " + name); 109 | return true; 110 | } 111 | catch 112 | { 113 | Debug.WriteLine("Error occurred deleting consumer type (" + ConsumerClass + ") named: " + name); 114 | } 115 | return false; 116 | } 117 | 118 | private bool RemoveBinding(string WmiPath) 119 | { 120 | try 121 | { 122 | ManagementObject binding = new ManagementObject(WmiPath); 123 | binding.Delete(); 124 | Debug.WriteLine("Successfully deleted WMI event binding: " + WmiPath); 125 | return true; 126 | } 127 | catch 128 | { 129 | Debug.WriteLine("Error occurred deleting WMI event binding: " + WmiPath); 130 | } 131 | return false; 132 | } 133 | 134 | private void BtnRemoveFilter_Click(object sender, EventArgs e) 135 | { 136 | if (RemoveFilter(ListFilters.SelectedItems[0].Text)) 137 | { 138 | ListFilters.Items.Remove(ListFilters.SelectedItems[0]); 139 | } 140 | } 141 | 142 | private void ComboConsumerType_SelectedIndexChanged(object sender, EventArgs e) 143 | { 144 | ComboBox senderComboBox = (ComboBox)sender; 145 | 146 | PopulateConsumers(senderComboBox.SelectedItem.ToString()); 147 | } 148 | 149 | private void BtnRemoveConsumer_Click(object sender, EventArgs e) 150 | { 151 | // Get the selected WMI event consumer from the ListView 152 | ListViewItem SelectedConsumer = ListConsumers.SelectedItems[0]; 153 | // Get the index of the selected consumer 154 | Int32 SelectedConsumerIndex = SelectedConsumer.Index; 155 | 156 | // Remove the consumer with the specified name and consumer type 157 | if (RemoveConsumer(SelectedConsumer.Text , ComboConsumerType.SelectedItem.ToString())) 158 | { 159 | ListConsumers.Items.Remove(SelectedConsumer); 160 | MessageBox.Show(SelectedConsumerIndex.ToString()); // debugging only 161 | 162 | // Select the item that took the place of the previously selected item 163 | if (ListConsumers.Items.Count -1 >= SelectedConsumerIndex) { ListConsumers.Items[SelectedConsumerIndex].Selected = true; } 164 | else if (ListConsumers.Items.Count > 1) { ListConsumers.Items[SelectedConsumerIndex - 1].Selected = true; } 165 | else if (ListConsumers.Items.Count == 1) { ListConsumers.Items[0].Selected = true; } 166 | 167 | // Set focus to the ListConsumers object 168 | ListConsumers.Select(); 169 | } 170 | } 171 | 172 | private void ButtonRemoveBinding_Click(object sender, EventArgs e) 173 | { 174 | if (RemoveBinding(ListBoxBindings.SelectedItem.ToString())) 175 | { 176 | ListBoxBindings.Items.Remove(ListBoxBindings.SelectedItem.ToString()); 177 | } 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Form1.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Windows.Forms; 5 | using System.Security.Principal; 6 | 7 | namespace WmiEventHelper 8 | { 9 | static class Program 10 | { 11 | /// 12 | /// The main entry point for the application. 13 | /// 14 | [STAThread] 15 | static void Main() 16 | { 17 | Application.EnableVisualStyles(); 18 | Application.SetCompatibleTextRenderingDefault(false); 19 | if (CheckAdmin()) 20 | { 21 | Application.Run(new FormWmiEventHelper()); 22 | } 23 | else 24 | { 25 | MessageBox.Show("You are not an administrator. Please run this application as an administrator."); 26 | } 27 | } 28 | 29 | private static bool CheckAdmin() 30 | { 31 | WindowsIdentity identity = WindowsIdentity.GetCurrent(); 32 | WindowsPrincipal principal = new WindowsPrincipal(identity); 33 | bool IsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); 34 | return IsAdmin; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("WmiEventHelper")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Microsoft")] 12 | [assembly: AssemblyProduct("WmiEventHelper")] 13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("1ce5c78c-951a-4753-b4e8-462936c7d1ff")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.1 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WmiEventHelper.Properties { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WmiEventHelper.Properties.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.1 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WmiEventHelper.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/WmiEventHelper.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | x86 6 | 8.0.30703 7 | 2.0 8 | {6D02E948-C6AB-4444-B19E-E48DD9D83F14} 9 | WinExe 10 | Properties 11 | WmiEventHelper 12 | WmiEventHelper 13 | v3.5 14 | Client 15 | 512 16 | 17 | 18 | x86 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | x86 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | Form 51 | 52 | 53 | Form1.cs 54 | 55 | 56 | 57 | 58 | Form1.cs 59 | 60 | 61 | ResXFileCodeGenerator 62 | Resources.Designer.cs 63 | Designer 64 | 65 | 66 | True 67 | Resources.resx 68 | True 69 | 70 | 71 | 72 | SettingsSingleFileGenerator 73 | Settings.Designer.cs 74 | 75 | 76 | True 77 | Settings.settings 78 | True 79 | 80 | 81 | 82 | 89 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/WmiEventHelper.idc: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/bin/Debug/WmiEventHelper.exe.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/bin/Debug/WmiEventHelper.vshost.exe.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /WmiEventHelper/WmiEventHelper/bin/Debug/WmiEventHelper.vshost.exe.manifest: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | --------------------------------------------------------------------------------