Home > Blockchain >  compare array of string with json object property
compare array of string with json object property

Time:12-18

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 ?

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

CodePudding user response:

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')

CodePudding user response:

Using Compare-Object:

(Compare-Object -ReferenceObject $AllDrives.DriveLetter -DifferenceObject $StandardDrives).InputObject

will return:

J
K

CodePudding user response:

here is yet another way to get the drive letters that are not in use. [grin]

what it does ...

  • defines the list of possible drive letters
  • uses the .Where() collection method to filter things
  • checks to see if the possible letter is in the in-use letter collection
  • outputs that to the success stream
    that can be captured to a $Var by assigning it to one.

the code ...

@('e', 'f', 'g', 'h', 'i', 'j', 'k').Where({
    $_ -notin $AllDrives.DriveLetter
    })

output ...

j
k
  • Related