Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0

How to delete entries when a specific object property does not exists in Powershell?


For example, in the following PSCustomObject, I wish to remove the objects for which TagName does not exist

$dataset1 = @(
    @{
        MachineName = "AAA"
        ID   = "111"
        TagName = "GroupA"
    },
    @{
        MachineName = "BBB"
        ID   = "222"
        TagName = "GroupB"
    },
    @{
        MachineName = "CCC"
        ID   = "111"
        TagName = ""
    },
    @{
        MachineName = "DDD"
        ID   = "333"
        TagName = ""
    },
    @{
        MachineName = "EEE"
        ID   = "111"
        TagName = ""
    }
    }

So, after deletion the $dataset1 should contain the following:

$dataset1 = @(
    @{
        MachineName = "AAA"
        ID   = "111"
        TagName = "GroupA"
    },
    @{
        MachineName = "BBB"
        ID   = "222"
        TagName = "GroupB"
    }
   }

Solution

  • You can use Where-Object(or alias name where). Where-Object returns all objects for which the script block statement is true

    $dataset1 = $dataset1 | Where-Object { $_.TagName }