resolver101
resolver101

Reputation: 2255

PowerShell: Comparing 2 variables

Can anyone tell me why the code below is not working? I want to end up with the drives that match both e.g. F: and G:

I know its something simple but cant figure it out. A quick explanation would be welcome. Thanks

$USBDrives =$null 
$WMIUSBDrives="E:","F:","G:"
$SystemDrives="D:","F:","G:"
$USBDrives = $SystemDrives | Where {$_ -contains $WMIUSBDrives}
$USBDrives

Upvotes: 0

Views: 2944

Answers (2)

Arcass
Arcass

Reputation: 932

For the above to work, I think $WMIUSBDrives and $SystemDrives would have to match.

Try this instead:

$USBDrives =$null 
$WMIUSBDrives="E:","F:","G:"
$SystemDrives="D:","F:","G:"
foreach($drive in $WMIUSBDrives)
{
    if($SystemDrives  -contains $drive){$USBDrives += $drive}
}
$USBDrives

Upvotes: 0

BartekB
BartekB

Reputation: 8660

You actually should use this other way around... :)

$USBDrives = $SystemDrives | Where {$WMIUSBDrives -contains $_}
$USBDrives

The operator that works the way you want is -in that was added in v3. HTH Bartek

Upvotes: 3

Related Questions