Group-Object Powershell 2.0

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Poshoholic Poshoholic 4 years ago.

  • Author
    Posts
  • #7294
    Profile photo of Oliver Adams
    Oliver Adams
    Participant

    The function below Works fine in PowerShell 3.0 but only displays the Count in Powershell 2.0.

    Function Get-OAEventLog {

    param([Parameter(Mandatory=$True)]$LogName)

    Get-EventLog -LogName $LogName -EntryType Error,Warning |
    Select-Object EventID,TimeGenerated,Message |
    Group-Object EventID |
    Select-Object Count,`
    @{Name='Between';Expression={$_.Group.TimeGenerated[0],$_.Group.TimeGenerated[($_.Group.TimeGenerated.Count – 1)]}},`
    @{Name='EventID';Expression={$_.Group.EventID[0]}},`
    @{Name='Message';Expression={IF($_.Group.Message.Count -gt 1){ $_.Group.Message[0]} Else {$_.Group.Message }}}
    }

    Get-OAEventLog -LogName Application

  • #7298
    Profile photo of Poshoholic
    Poshoholic
    Member

    You're right. Was there a question?

    If you're wondering why that function doesn't work the same way in PowerShell 2.0, it's because you're referencing properties on the objects that are part of the group (e.g. $_.Group.TimeGenerated, $_.Group.EventId, $_.Group.Message). PowerShell 3.0 allows you to directly reference properties on objects in a collection, but PowerShell 2.0 did not have that capability. To make this work in PowerShell 2.0, you'll have to replace each of these with something that does work in the older version.

    For example, this:

    $_.Group.TimeGenerated

    would have to be replaced with this:

    @($_.Group | Select-Object -ExpandProperty TimeGenerated)

    Since you're using it multiple times inside of one expression, you probably only want to do that pipeline once, store it in a variable, and then use that variable in the remainder of the expression.

    Similar changes are required for $_.Group.EventID and $_.Group.Message.

  • #7308
    Profile photo of Oliver Adams
    Oliver Adams
    Participant

    That is an amazing reply and sorry for not actually posting a question. The things you do when you are in a hurry! Thanks again this really helps.

  • #7402
    Profile photo of Oliver Adams
    Oliver Adams
    Participant

    Is there a way for me to mark your answer as correct? or mark this as solved or shall I just change the title?

  • #7403
    Profile photo of Poshoholic
    Poshoholic
    Member

    This forum software doesn't support marking posts as solved or answers as correct, so you can just change the title if you want to make sure others see it is resolved. We archive posts regularly though, so you can also just leave it as is and it will get archived later.

You must be logged in to reply to this topic.