Reputation: 12213
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")
Upvotes: 0
Views: 251
Reputation: 7479
here is yet another way to get the drive letters that are not in use. [grin]
what it does ...
.Where()
collection method to filter thingsthe code ...
@('e', 'f', 'g', 'h', 'i', 'j', 'k').Where({
$_ -notin $AllDrives.DriveLetter
})
output ...
j
k
Upvotes: 2
Reputation: 26094
Using Compare-Object
:
(Compare-Object -ReferenceObject $AllDrives.DriveLetter -DifferenceObject $StandardDrives).InputObject
will return:
J
K
Upvotes: 1
Reputation: 174575
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')
Upvotes: 3