Skip to content

Make Get-WinEvent compatible to Get-EventLog #15844

Closed

Description

Summary of the new feature / enhancement

For decades, Windows admins have been using Get-EventLog to query classic event logs. In PowerShell 3, Get-EventLog was superseeded by the more powerful and versatile Get-WinEvent which technically has convincing features: it is faster, accepts sophisticated xml queries, can access evtx based event logs, and more.

However, Get-WinEvent was never really adopted by the community, and still Get-EventLog is used most often. In PowerShell Core, Get-Eventlog was actually removed from the package so users hooked to Get-EventLog are faced with code changes.

The primary reason just why users did not adopt the technically superior Get-WinEvent is simple: its user interface is awkward and non-discoverable. To perform an average query, at minimum a FilterHashtable is needed, and its predefined supported keys are not discoverable. So a user would have to google and investigate which keys are needed when in contrast, Get-EventLog would simply suggest intuitive parameters.

Since the new Get-WinEvent can do what Get-EventLog did (and more and faster), this cmdlet should simply support the old parametersets from Get-EventLog and translate them into the awkward filter hashtable keys.

Current Situation

Here is an average event log query using Get-EventLog returning the installed updates within the past 30 days:

$30Days = (Get-Date).AddDays(-30)
Get-Eventlog -LogName System -EntryType Information -InstanceId 19 -After $30Days -Source 'Microsoft-Windows-WindowsUpdateClient'

With Get-WinEvent, a user would have to compose at minimum a filter hashtable like so:

$30Days = (Get-Date).AddDays(-30)
$filter = @{
    LogName = 'System'
    Level = 4,5
    Id = 19
    StartTime = $30Days
    ProviderName = 'Microsoft-Windows-WindowsUpdateClient'
}
Get-WinEvent -FilterHashtable $filter

None of the hashtable keys needed here is discoverable. They are not intuitive, there is no intellisense or completion, thus a user would have to go google.

That said, once the correct filter hashtable has been composed, Get-WinEvent returns the very same information (albeit property names may differ a little, this would be something admins can easily work around).

Suggestion

By adding the parameters supported by Get-EventLog to Get-WinEvent, the cmdlet could automate the process of composing the filter hashtable. In essence, Get-WinEvent would be usable just as easily as Get-EventLog has been for years. This would ease transition to PowerShell Core and also increase the performance of event log queries altogether.

With such a concept, the user would run Get-WinEvent like this:

$30Days = (Get-Date).AddDays(-30)
Get-WinEvent -LogName System -EntryType Information -InstanceId 19 -After $30Days -Source 'Microsoft-Windows-WindowsUpdateClient'

Proposed technical implementation details (optional)

The implementation is primarily diligence work and not technically challenging. Basically, the parameters have to be translated to the appropriate hashtable keys.

Below is a proof of concept which is obviously neither complete nor production ready. I added the most commonly used parameters used by Get-EventLog. I did not i.e. implement the list parameterset (which should be trivial enough).

<#
Suggestion to improve Get-WinEvent in order to make it compatible to the commonly used Get-EventLog calls

Below is a prototype using a proxy function. Run it to enhance Get-WinEvent.
To get rid of the enhancement, either restart PowerShell or run:
Remove-Item -Path function:Get-WinEvent

Note that the prototype emits the composed hashtable to the console (green)
#>

function Get-WinEvent
{
    [CmdletBinding(DefaultParameterSetName='GetLogSet', HelpUri='https://go.microsoft.com/fwlink/?LinkID=138336')]
    param(
        
        [Parameter(ParameterSetName='ListLogSet', Mandatory=$true, Position=0)]
        [AllowEmptyCollection()]
        [string[]]
        ${ListLog},

        [Parameter(ParameterSetName='LogNameGetEventlog', Mandatory=$true, Position=0)] <#NEW#> 
        [Parameter(ParameterSetName='GetLogSet', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [string[]]
        ${LogName},

        [Parameter(ParameterSetName='ListProviderSet', Mandatory=$true, Position=0)]
        [AllowEmptyCollection()]
        [string[]]
        ${ListProvider},

        <# Get-EventLog supports wildcards, Get-WinEvent does not. Needs to be corrected. #>
        [Parameter(ParameterSetName='GetProviderSet', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)]
        [string[]]
        ${ProviderName},

        [Parameter(ParameterSetName='FileSet', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)]
        [Alias('PSPath')]
        [string[]]
        ${Path},

        [Parameter(ParameterSetName='FileSet')]
        [Parameter(ParameterSetName='GetProviderSet')]
        [Parameter(ParameterSetName='GetLogSet')]
        [Parameter(ParameterSetName='HashQuerySet')]
        [Parameter(ParameterSetName='XmlQuerySet')]
        [ValidateRange(1, 9223372036854775807)]
        [long]
        ${MaxEvents},
        
        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [ValidateRange(0, 2147483647)]
        [int]
        ${Newest},
        
        [Parameter(ParameterSetName='GetProviderSet')]
        [Parameter(ParameterSetName='ListProviderSet')]
        [Parameter(ParameterSetName='ListLogSet')]
        [Parameter(ParameterSetName='GetLogSet')]
        [Parameter(ParameterSetName='HashQuerySet')]
        [Parameter(ParameterSetName='XmlQuerySet')]
        [Parameter(ParameterSetName='LogNameGetEventlog')] <#NEW#> 
        [Alias('Cn')]
        [ValidateNotNullOrEmpty()] <#CORRECTED#>
        [string] <# used to be [String[]], Get-WinEvent accepts [string] only, should be changed to accept string arrays #>
        ${ComputerName},

        [Parameter(ParameterSetName='GetProviderSet')]
        [Parameter(ParameterSetName='ListProviderSet')]
        [Parameter(ParameterSetName='ListLogSet')]
        [Parameter(ParameterSetName='GetLogSet')]
        [Parameter(ParameterSetName='HashQuerySet')]
        [Parameter(ParameterSetName='XmlQuerySet')]
        [Parameter(ParameterSetName='FileSet')]
        [pscredential]
        [System.Management.Automation.CredentialAttribute()]
        ${Credential},

        [Parameter(ParameterSetName='FileSet')]
        [Parameter(ParameterSetName='GetProviderSet')]
        [Parameter(ParameterSetName='GetLogSet')]
        [ValidateNotNull()]
        [string]
        ${FilterXPath},

        [Parameter(ParameterSetName='XmlQuerySet', Mandatory=$true, Position=0)]
        [xml]
        ${FilterXml},

        [Parameter(ParameterSetName='HashQuerySet', Mandatory=$true, Position=0)]
        [hashtable[]]
        ${FilterHashtable},

        [Parameter(ParameterSetName='GetProviderSet')]
        [Parameter(ParameterSetName='ListLogSet')]
        [Parameter(ParameterSetName='GetLogSet')]
        [Parameter(ParameterSetName='HashQuerySet')]
        [switch]
        ${Force},

        [Parameter(ParameterSetName='GetLogSet')]
        [Parameter(ParameterSetName='GetProviderSet')]
        [Parameter(ParameterSetName='FileSet')]
        [Parameter(ParameterSetName='HashQuerySet')]
        [Parameter(ParameterSetName='XmlQuerySet')]
        [switch]
        ${Oldest},
    
        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [ValidateNotNullOrEmpty()]
        [datetime]
        ${After},

        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [ValidateNotNullOrEmpty()]
        [datetime]
        ${Before},
        
        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [ValidateNotNullOrEmpty()]
        [string[]]
        ${UserName},

        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog', Position=1)]
        [ValidateRange(0, 9223372036854775807)]
        [ValidateNotNullOrEmpty()]
        [long[]]
        ${InstanceId},

        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [ValidateNotNullOrEmpty()]
        [ValidateRange(1, 2147483647)]
        [int[]]
        ${Index},

        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [Alias('ET')]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('Error','Information','FailureAudit','SuccessAudit','Warning')]
        [string[]]
        ${EntryType},

        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [Alias('ABO')]
        [ValidateNotNullOrEmpty()]
        [string[]]
        ${Source},

        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [Alias('MSG')]
        [ValidateNotNullOrEmpty()]
        [string]
        ${Message},

        <# NEW #>
        [Parameter(ParameterSetName='LogNameGetEventlog')]
        [switch]
        ${AsBaseObject},
        
        [Parameter(ParameterSetName='ListGetEventlog')]
        [switch]
        ${List},

        [Parameter(ParameterSetName='ListGetEventlog')]
        [switch]
        ${AsString}
        
        
        
    )

    begin
    {
        try {
            $outBuffer = $null
            if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
            {
                $PSBoundParameters['OutBuffer'] = 1
            }
            $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Diagnostics\Get-WinEvent', [System.Management.Automation.CommandTypes]::Cmdlet)

            # if the user chose the Get-EventLog compatible parameters,
            # compose the appropriate filterhashtable:
            $scriptCmd = if ($PSCmdlet.ParameterSetName -eq 'LogNameGetEventlog')
            {
                # mandatory parameter:
                $filter = @{
                    LogName = $PSBoundParameters['Logname']
                }
                $null = $PSBoundParameters.Remove('LogName')
                
                if ($PSBoundParameters.ContainsKey('Before'))
                {
                    $filter['EndTime'] = $PSBoundParameters['Before']
                    $null = $PSBoundParameters.Remove('Before')
                }
                if ($PSBoundParameters.ContainsKey('After'))
                {
                    $filter['StartTime'] = $PSBoundParameters['After']
                    $null = $PSBoundParameters.Remove('After')
                }
                if ($PSBoundParameters.ContainsKey('EntryType'))
                {
                    # severity is translated to an integer array:
                    
                    $levelFlags = [System.Collections.Generic.List[int]]@()

                    # string input converted to integer array:
                    if ($PSBoundParameters['EntryType'] -contains 'Error')
                    {
                        $levelFlags.Add(1) # critical
                        $levelFlags.Add(2) # error
                    }
                    if ($PSBoundParameters['EntryType'] -contains 'Warning')
                    {
                        $levelFlags.Add(3) # warning
                    }
                    if ($PSBoundParameters['EntryType'] -contains 'Information')
                    {
                        $levelFlags.Add(4) # informational
                        $levelFlags.Add(5) # verbose
                    }
                    
                        
                    # default to 0:
                    if ($levelFlags.Count -gt 0)
                    {
                        $filter['Level'] = [int[]]$levelFlags
                    }
                        
                    # audit settings stored in Keywords key:
                    if ($PSBoundParameters['EntryType'] -contains 'FailureAudit')
                    {
                        $filter['Keywords'] += 0x10000000000000
                    }
                    if ($PSBoundParameters['EntryType'] -contains 'SuccessAudit')
                    {
                        $filter['Keywords'] += 0x20000000000000
                    }
                    $null = $PSBoundParameters.Remove('EntryType')
                }
                if ($PSBoundParameters.ContainsKey('InstanceId'))
                {
                    $filter['ID'] = $PSBoundParameters['InstanceId']
                    $null = $PSBoundParameters.Remove('InstanceId')
                }
                if ($PSBoundParameters.ContainsKey('Source'))
                {
                    $filter['ProviderName'] = $PSBoundParameters['Source']
                    $null = $PSBoundParameters.Remove('Source')
                }
                
                $PSBoundParameters['FilterHashtable'] = $filter
                Write-Host ($filter | Out-String) -ForegroundColor Green
                
                if ($PSBoundParameters.ContainsKey('Newest'))
                {
                    $PSBoundParameters['MaxEvents'] = $PSBoundParameters['Newest']
                    $null = $PSBoundParameters.Remove('Newest')
                }
            }
            
            
            $scriptCmd = 
            {
                & $wrappedCmd @PSBoundParameters
            } 
            $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
            $steppablePipeline.Begin($PSCmdlet)
        } catch {
            throw
        }
    }

    process
    {
        try {
            $steppablePipeline.Process($_)
        } catch {
            throw
        }
    }

    end
    {
        try {
            $steppablePipeline.End()
        } catch {
            throw
        }
    }
    <#

            .ForwardHelpTargetName Microsoft.PowerShell.Diagnostics\Get-WinEvent
            .ForwardHelpCategory Cmdlet

    #>

}

Once you run this code, you can then continue to use Get-WinEvent like before, but you now can also start using the parameters that you know from Get-EventLog. The enhanced Get-WinEvent automatically converts these parameters into a filterhashtable, and there is no need anymore for the user to know its keys or predefined awkward codes for event types.

Notes

There are a few technical limitations, i.e. Get-EventLog supports wildcards for providernames whereas Get-WinEvent does not. Get-WinEvent should be enhanced in these areas to be on the same level.

Obviously the new parameters should get rich intellisense to suggest available lognames and provider names.

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Jul 29, 2021
  2. iSazonov commented on Jul 29, 2021

    @iSazonov
    Collaborator

    In general, I very like this idea of making this cmdlet more friendly. However, I think that this is not the right way to emulate the old cmdlet (which is also not without its flaws) that can mislead users.
    We could add more parameters in new parameter set.
    But I'd start with investigation whether we enhance tab completion for FilterHashtable parameter (don't forget about new predictor API!).

    Below is a proof of concept which is obviously neither complete nor production ready.

    I don't see a point to keep the issue open. I suggest to continue in Discussions or on other community resources and come back with final proposal which ready for approval and implementation.

    So a user would have to google and investigate which keys are needed when in contrast, Get-EventLog would simply suggest intuitive parameters.

    The cmdlet has 16 examples in docs. If that's not enough you could contribute to the docs.

  3. added
    WG-Cmdlets
    on Jul 29, 2021
  4. MartinGC94 commented on Jul 29, 2021

    @MartinGC94
    Contributor

    IMO hashtables with or without completion for the key/values don't feel as good to use interactively as real parameters do. The reason for this is all the extra characters you have to write @{}; + the quotes around string values.
    In scripts hashtables are great because of how easy they are to read (especially when they are aligned properly).

    How do people typically use the event log cmdlets? Directly from the CLI? Or in scripts? I personally only use them to make smaller functions like getting the last boot time or whatever so I don't mind the current syntax (although completions for the hashtable would definitely be appreciated).

  5. TobiasPSP commented on Jul 30, 2021

    @TobiasPSP
    CollaboratorAuthor

    However, I think that this is not the right way to emulate the old cmdlet (which is also not without its flaws) that can mislead users.

    I don't see a point to keep the issue open. I suggest to continue in Discussions or on other community resources and come back with final proposal which ready for approval and implementation.

    The cmdlet has 16 examples in docs. If that's not enough you could contribute to the docs.

    Why would adding well established parameters be misleading? After all, Get-WinEvent already is providing parameter sets for hashtable, xlm and xpath input, so it is tailored towards many different target audiences already. I think we should add the primary target audience „admins“ which often don‘t even know what a „hashtable“ is.

    In fact, asking user input via structures of any kind - hashtable, xpath, etc - is not the way how powershell cmdlets typically work. Typically, cmdlets prompt for user information via discoverable parameters. The fact that Get-Eventlog is still in wide use in WPS/industrial whereas Get-WinEvent is not, vividly illustrates this dilemma.

    So why not just adding parameters that have been in common use for many years and do the job, especially since changes are trivial in comparison to adding intellisense for hashtable keys (which is definitely a great suggestion as yet another enhancement for that particular parameterset).

  6. TobiasPSP commented on Jul 30, 2021

    @TobiasPSP
    CollaboratorAuthor

    To go a step further to improve practical usability for admins, I'd suggest that Get-WinEvent should expose the "Properties" property content as a direct object array.

    Most of the time, when reading the eventlog, people are after the real "beef" which is embedded in a static "message" template. The embedded "beef" that is inserted in this template currently surfaces in the "Properties" property.

    Rather than taking message and using string manipulation and RegEx to get to the actual event information, "Properties" provides object-oriented access.

    However, "Properties" is an array of type "EventProperty" which inside stores the actual value in "Value". It has no other property and is a simple wrapper, so there is no extra value in keeping this object vs. returning its value property directly.
    "Unrolling" that value and returning a simple object array of values would make this information more accessible.

    To not run into compatibility issues, this could be implemented as a scriptproperty "Values", for example. It would be a simple enhancement of the ps1xml.

    Current Situation

    Currently values need to be unrolled. If I just wanted to know which software was installed on my system within the past 30 days, I'd need something like this:

    $30Days = (Get-Date).AddDays(-30)
    $filter = @{
        LogName = 'System'
        Level = 4,5
        Id = 19
        StartTime = $30Days
        ProviderName = 'Microsoft-Windows-WindowsUpdateClient'
    }
    Get-WinEvent -FilterHashtable $filter | Select-Object -Property TimeGenerated, @{N='Values'; E={ $_.Properties | Foreach-Object { $_.Value }}}

    If I tried to intuitively enumerate "Properties", this would provide a list of EventProperty objects, not the values that I'd expect:

    Get-WinEvent -FilterHashtable $filter | Select-Object -Property TimeGenerated, @{N='Values'; E={ $_.Properties }}

    Suggested Outcome

    With a new "Values" scriptproperty, non-programmers would have a much easier and intuitive way of accessing the values:

    Get-WinEvent -FilterHashtable $filter | Select-Object -Property TimeGenerated, @{N='Values'; E={ $_.Values }}
  7. TobiasPSP commented on Jul 30, 2021

    @TobiasPSP
    CollaboratorAuthor

    The cmdlet has 16 examples in docs. If that's not enough you could contribute to the docs.

    While it's of course a good thing to have rich examples, in this patricular instance the number of examples is the symptom of the problem, not the cure. 16 examples are not enough here because not a single one of them explains how to do basic routine tasks, and adding more examples will only add to the confusion. It's a flaw in the user interface that is too complex.

    Don't take my word for it. Let's look at reality and assume an admin needs to dump error events to quickly find out what's wrong with a server. That's a common task, and that's why 'Get-WinEvent' exists.

    With the deprecated Get-EventLog, solving this problem takes seconds since this cmdlet adheres to the sacred PowerShell principles and provides filter parameters named exactly like the properties it filters. The user can recycle entry-level PowerShell knowledge: by looking at the cmdlet output, immediately identifies the "column" EntryType and uses the parameter -EntryType to filter - mission accomplished in 10 seconds.

    With Get-WinEvent, the user finds no intuitive parameter to filter. So the user is forced to resort to the documentation ("but I just wanted errors - do I really need that?").

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/get-winevent?view=powershell-7.1

    It takes the user now 10 examples until finally example #10 claims to solve his problem: Get error events that have a specified string in their name. Unfortunately this example isn't doing what its title claims. It is in fact not related to error events at all. It simply does an expensive client-side grouping for LevelDisplayName (which BTW is bad practice).

    So the user continues to read on while the server is sitting there malfunctioning and the boss is getting nervous. Example #17 is the next one that seems promising: Use FilterHashtable to get application errors. Bad luck again: it simply filters for a provider name that just happens to report errors. No error filtering again. This is filtering for a provider name, not errors.

    No more examples related to his issue - an issue that is trivial and at the core of what Get-WinEvent should do.

    Even if the user was so experienced as to suspect that the parameter -FilterHashtable might be of help here, the documentation of this parameter just lists supported key names - but neither their purpose nor required values, so again no success. The required hashtable key Level isn't intuitive in the first place, but without the numeric code values it is of no use anyway (1=Critical, 2=Error, 3=Warning,...)

    Essence: the user is unable to successfully perform this trivial task because both the user interface design and the documentation of Get-WinEvent currently are of low usability.

    So from daily experience in hundreds of companies and IT departments, I wrapped my head around it and wondered what could be really helpful for this particular audience to actually master their daily business with Get-WinEvent. They already know Get-EventLog and never had issues with it, so adding the old user interface back to the new cmdlet seems simple and effective.

    I know we all come from different areas and have different focus, background and experience. I hope this real-world scenario can illustrate a tiny bit why I am proposing this change and why I think it is important.

    We can work on symptoms (documentation, intellisense for hashtables) but primarily we should cure the cause which is a user interface that is inappropriate for the primary target audience and needs too much explaining.

    Plus the suggested change is so trivial.

    The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs. The cmdlet gets data from event logs that are generated by the Windows Event Log technology introduced in Windows Vista. And, events in log files generated by Event Tracing for Windows (ETW). By default, Get-WinEvent returns event information in the order of newest to oldest. Get-WinEvent lists event logs and event log providers. To interrupt the command, press CTRL+C. You can get events from selected logs or from logs generated by selected event providers. And, you can combine events from multiple sources in a single command. Get-WinEvent allows you to filter events using XPath queries, structured XML queries, and hash table queries. If you're not running PowerShell as an Administrator, you might see error messages that you cannot retrieve information about a log.
  8. iSazonov commented on Jul 30, 2021

    @iSazonov
    Collaborator

    Four years ago, I made a few fixes and improvements to this cmdlet and left the work because there was no feedback. So, thank you for paying attention to this cmdlet. At that time I was thinking about how to make this cmdlet smarter and more useful, but because of the passage of time I don't remember all details anymore. (I consider some QBE scenarios in particular.)

    My concern about "emulation" is that would confuse users because they would expect this works the same but it's not since another underlying API is used. Moreover, I suppose we can make this cmdlet more smart than just copying the parameters.

    This cmdlet has much more features and better performance than Get-EventLog but I agree that it is harder to use. A root of the problem is user don't know and don't see meta information of events. The main difficulty is that each type of event has a different format.
    Moreover evtx format is so flexible that either there could be no meta information at all (which has to be taken elsewhere, in a SDK), or there could be self-describing events or the log file could have a manifest.

    As you see it is not easy to find a common approach.

    I would suggest:

    • QBE approach
    • XML parameter to generate XML formatted output based on meta information in the event
    • Expand parameter to convert EventLogRecord class to PSCustomObject based on meta information in the event
    • Metadata parameter to output either log manifest in readable format or metadata for self-describing event.

    I may have had other ideas, but I don't remember because of the passage of time.

  9. SteveL-MSFT commented on Aug 2, 2021

    @SteveL-MSFT
    Member

    I wonder if a New-WinEventFilter cmdlet which has parameters and simply returns a hashtable would be a good experience? Perhaps even allow piping that result directly into Get-WinEvent?

  10. vexx32 commented on Aug 3, 2021

    @vexx32
    Collaborator

    It'd be fine and possibly even better if it returned a concrete type with those values being publicly settable, I think; powershell folks could still use a hashtable as the parameter as long as the parameter type is the new type, and it allows the properties to be publicly set.

    The error messages during parameter binding would be pretty decent, and you have the benefit of being able to auto-gen help content for those type members that you can reference from the cmdlet(s) help files.

  11. TobiasPSP commented on Aug 3, 2021

    @TobiasPSP
    CollaboratorAuthor

    I wonder if a New-WinEventFilter cmdlet which has parameters and simply returns a hashtable would be a good experience?

    I thought about that, too, but there are good reasons why IMHO this should be a new parameterset inside Get-WinEvent:

    • Consistency: internally, Get-WinEvent uses XML to do the query, so -FilterXPath. -FilterXML and -FilterHashtable as well as some distinct parameters such as -Logname all take user input and transform it into the appropriate XML query. The suggested new parameters would adopt the same principle.
    • Simplicity: separating the query into two cmdlets provides no extra value. Currently, when you submit -Verbose, Get-WinEvent emits the composed XML as a verbose stream. This should be the same here, too, so when a user uses the suggested parameter set, we should emit the constructed hashtable to the verbose stream as well.
    • No API: cmdlets are the primary user interface and not a backend API. So we shouldn't treat Get-WinEvent as a backend API that is accessible through another cmdlet with the real user interface. That's what parametersets are typically used for.

    Adding a new parameterset to the cmdlet isn't really a hard thing to do, and I can't see any compatibility issues or added complexity.

  12. TobiasPSP commented on Aug 3, 2021

    @TobiasPSP
    CollaboratorAuthor

    My concern about "emulation" is that would confuse users because they would expect this works the same but it's not since another underlying API is used. Moreover, I suppose we can make this cmdlet more

    I hear you, and I would see the same problem if we named the cmdlet smilar, i.e. Get-EventLog or Get-EventLogEx. This would raise the expectation of similar output.

    I am focusing on input though. It is common place in PowerShell cmdlets that parameter names are standardized, i.e. Path, Filter, etc. even though users understand that they can have slightly different effects with different cmdlets. So duplicate parameter names isn't a problem, rather the cure and a good practice in PowerShell.

    I have conducted extensive testincg, so that said, and even though we are using a different API, the suggested parameters in fact work exactly like the ones in Get-EventLog. Again, the parameters are for filtering, and after all both cmdlets access the same event data.

    Just the output is in a different format. Since cmdlet names are sufficiently different, IMHO there is no risk of confusing these two. A user who simply exchanges the cmdlet names in old scripts (thanks to parameter compatibility) can't complain that output is different. Same with Get-WmiObject and Get-CimInstance.

  13. iSazonov commented on Aug 3, 2021

    @iSazonov
    Collaborator

    I wonder if a New-WinEventFilter cmdlet which has parameters and simply returns a hashtable would be a good experience?

    It is trivial for common event properties but it's hard for specific event properties.
    OOB in Windows there are hundreds of event providers, each of which can have tens of event types, i.e. there are tens of thousands of event types. Extracting meta-information for all of them would take a few minutes. (And remember that not all of them have static metadata, i.e. we cannot always use caching>)

    The only scenario we could implement is with strict adherence to the following steps:

    1. Pick up an event provider (read and cache metadata)
    2. Pick up an event number
    3. Search metadata for the event (the event provider + the event number)
    4. Get specific properties for the event

    This force we think about dynamic parameters. Although I'm not sure if there are any multi-level nesting. if no we could enhance Get-WinEvent with dynamic parameters (PSPropertyExpression?) without introducing new cmdlet (New-WinEventFilter).

    Just the output is in a different format.

    That's exactly what I'm talking about. It makes it harder for users to adapt than it helps them. Why make a Tesla a steamroller? :-)
    That goes for internal implementation as well. It's better to fully utilize the power of the new API than to try to waste it on primitive things

    IMHO there is no risk of confusing these two

    I can not agree with this. I think it is high risk to break something and tricky.

    I also had difficulty transitioning from Get-EventLog to Get-WinEvent. This happens quickly for scripts. Difficulties in interactive scripting. And there are ways to help users.

  14. TobiasPSP commented on Aug 3, 2021

    @TobiasPSP
    CollaboratorAuthor

    It'd be fine and possibly even better if it returned a concrete type with those values being publicly settable, I think; powershell folks could still use a hashtable as the parameter as long as the parameter type is the new type, and it allows the properties to be publicly set.

    I hope I understand the comment correctly. If not please apologize.

    My understanding is that rather than custom-build hand-tailored intellisense for a hashtable in this cmdlet, you suggest to replace it by some new object type that in itself (i.e. via its members) is discoverable.

    Since we cannot break compatibility, this would add a new parameterset as well. So the question would be whether the target user benefits more from yet another structured input object or from individual parameters that together compose the user input.

    The vast majority of PowerShell cmdlets receive user input via parameters with simple data types. Only very rarely do we see complex input objects. And if we do, these are either designed with piping in mind, or they support simple autoconversion from strings, so the user can always use simple data types to submit arguments.

    However discoverable you make a structural input, simply typing them into a single line, with special characters or artifical new lines via ";" or other complexities is cumbrsome.

    As a rule of thumb IMHO, complex input objects are ok if what you do happens is more related to scripting and programming, i.e. New-CimSessionOption creates such a "custom object" yet doing this is rarely needed interactively. Interactively, New-CimSession (as an example) surfaces the same known and proven parameters like -ComputerName and -Credential that are required and that even occasional scripters are familiar with.

    As a conclusion, daily tasks should IMHO be discoverable and doable via simple parameters. This helps occasional scripters and supports experienced admins when they do their typical production "trial and error" where they play with cmdlet outcome and add or remove individual parameters rather than having to edit separate complex structures.

    So maybe we should split this here into two different threads: there is definitely room to improve the existing filterhashtable parameterset and make it more discoverable. My proposal here focuses on a new parameterset trying to avoid complex structures altogether.

  15. TobiasPSP commented on Aug 3, 2021

    @TobiasPSP
    CollaboratorAuthor

    It is trivial for common event properties but it's hard for specific event properties.
    OOB in Windows there are hundreds of event providers, each of which can have tens of event types, i.e. there are tens of thousands of event types. Extracting meta-information for all of them would take a few minutes. (And remember that not all of them have static metadata, i.e. we cannot always use caching>)

    Maybe I am missing something here. When it comes to cmdlet input and typical filtering (as supported by -FilterHashtable), there are only a few parameters that almost exactly map Get-EventLog. We shouldn't try and go beyond -FilterHashtable without good reason.

    There are definitely additional sophisticated filter opportunities that go beyond what -FlterHashtable can do. For those rare circumstances where this is needed, users typically use -Verbose (to first create an initial XML from a simple filterhashtable), then use manual editing and re-submit tuned XPath. It was my feeling that the parametersets for XML exist exactly for this one scenario: to tap into the full and rich filtering backend. As far as I know, when you submit a -FilterXml, you already access the full API potential. Or am I missing something maybe?

    I am all for expanding the capabilities of this cmdlet while at it, provided these capabilities are what the majority of users need. Maybe we should get more concrete and come up with query examples that currently are not supported.

    Another thing is looking at cmdlet output. There is valuable information hidden inside the returned objects, namely inside the property Properties. I'd suggest we surface this as ordered hashtables, using numeric keys at first (in lack of metadata describing the names of these properties which are event specific), plus an optional parameter -PropertyName which can take an array of custom names that would replace the default numeric key names.

    That way, a user could simply pick the true property values needed from a given event type, manipulate the hashtable and "convert" it to [PSCustomObject] at last, producing beautiful object oriented output right from Get-WinEvent.

  16. TobiasPSP commented on Aug 3, 2021

    @TobiasPSP
    CollaboratorAuthor

    The initial suggestion was to add a cute little parameterset to have the every-day functionality that users are familiar with in Get-Eventlog. Technically this is trivial.

    Maybe we should separate discussions about (definitely promising) efforts to tap into metadata and create even more advanced queries to a new issue, or is this related to the suggested simple parameters, and I don’t see it yet?

  17. TobiasPSP commented on Aug 3, 2021

    @TobiasPSP
    CollaboratorAuthor

    It makes it harder for users to adapt than it helps them.

    Currently, the user I have in mind struggles with getting the cmdlet to run in the first place (see my earlier post explaining why users currently can't discover the functionality of Get-WinEvent). This user group (admins and ITPro) won't probably even notice that the returned data is wrapped inside a different type as long as they can read the data.

    It is a bit like with Get-WMIObject and Get-CimInstance. They basically return the same information but use different objects and have different concepts (COM vs. WSMan). I haven't seen problems, and people love the way how they can continue to use the same input information (WMI classes and filters) to get going.

  18. jdhitsolutions commented on Oct 20, 2021

    @jdhitsolutions
    Collaborator

    @PowerShell/wg-powershell-cmdlets reviewed this and don't believe New-EventLog is a cmdlet that most users use as it is more developer-oriented than for managing the event log. Since the EventLog cmdlet code is available in the PS repo under MIT License, a community member can use that and publish a standalone module to PowerShellGallery to get data of its utility before we revisit having this as part of PS7. Instead, the WinEvent cmdlets replace the EventLog cmdlets but we recognize that they are more complicated to use. We would prefer to focus the discussion on #15844 to improve the WinEvent cmdlets.

  19. ghost removed
    Needs-Triage
    on Oct 20, 2021
  20. iSazonov commented on Oct 20, 2021

    @iSazonov
    Collaborator

    Jeff Hicks (@jdhitsolutions) Is the link to #15844 correct in your post?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementWG-Cmdlets

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions