Home > Enterprise >  Simpler way to lookup an array / table?
Simpler way to lookup an array / table?

Time:10-29

I currently have a disk capacity report where i want to flag know exemptions for capacity problems. Currently I do this long hand like:

If ($Server.Name -eq "Server1" - And $Drive -eq "C:"){
  $Exemption = "Reason One"
}
If ($Server.Name -eq "Server2" - And $Drive -eq "E:"){
  $Exemption = "Reason Two"
}

etc.

what I would like to do is add the exemptions to a csv and import to a table/array/hash then just run a lookup to this and retirn the reason

sample csv layout like:

enter image description here

So is it possible in powershell to something like:

$table = import-csv my.csv 
If ($Server.Name -And $Drive match in $table){
   Exemption = $table.match.reason
}

CodePudding user response:

To get the value of the property "reason" from the csv in relation to the property "Server" and "Path" you can do:

$Exemption = ($table | ?{$_.server -eq $server.name -and $_.path -eq $drive).reason

If you want to set the value of $Exemption to 'none' if no matching recod is found in the csv you can do:

$reason = ($table | ?{$_.server -eq $server.name -and $_.path -eq $drive).reason
if ($reason){
   $exemption = $reason
}
Else {
   $exemption = 'none'
}
  • Related