Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

compare array of string with json object property

This is how my Input looks like:

$AllDrives = '[
    {
        "DriveLetter":  "F",
        "FileSystemLabel":  "Drive_F",
        "AllocationUnitSize":  4096
    },
    {
        "DriveLetter":  "E",
        "FileSystemLabel":  "Drive_E",
        "AllocationUnitSize":  4096
    },
    {
        "DriveLetter":  "H",
        "FileSystemLabel":  "",
        "AllocationUnitSize":  65536
    },
    {
        "DriveLetter":  "I",
        "FileSystemLabel":  "",
        "AllocationUnitSize":  65536
    },
    {
        "DriveLetter":  "G",
        "FileSystemLabel":  "",
        "AllocationUnitSize":  65536
    }
]' | ConvertFrom-Json

I want to compare another array with $AllDrives and return those elements from another array where DriveLetter is not matching with them.

$StandardDrives = @("E","F","G","H","I","J","K")

How do I accomplish this in (PowerShell way) without running two loops ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected output is @("J","K")

>Solution :

Use Where-Object and take advantage of property enumeration:

$StandardDrives |Where-Object {$_ -notin $AllDrives.DriveLetter}

When PowerShell sees that the $AllDrives array object does not have a DriveLetter property, it’ll automatically enumerate the values of DriveLetter on the individual array items instead, and the expression $AllDrives.DriveLetter thus expands to an array equivalent to @('F','E','H','I','G')

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading