简体   繁体   中英

Powershell Where command not working

I have a text file that contains elements separated by an '=' sign (ie color1=red, color2=blue, etc.

I used the import-csv command and provide headers (ie

$Import_Cfg = Import-Csv .\Env.cfg -Header Title,Setting -Delimiter =

)

Now this works fine if I want to assign a particular item to another variable if I know the index number and I have used that approach but it won't always work for me because I don't always know what other data will be there.

I thought that by using something like:

$MyColor1 = $Import_Cfg.Setting |where {$_.Title -match "Blue"}

$MyColor2 = $Import_Cfg.Setting |where {$_.Title -match "Red"}

it should work, but I get no returns for either item. When I type in $Import_cfg I can see the entire array (without the "=" signs). If I tell use the command

$MyColor1 = $import_cfg[0].setting 

I get the right answer.

Obviously I'm not using colors but a bunch of different items that I need to assign to variables for use elsewhere. Any thoughts on what I'm doing wrong? Everything I've read says that what I have above should work.

Please no flames on why I'm using import-csv vs get-content. I'm sure either will work. This is an approach that I've used and computationally it doesn't matter. If programatically it makes a difference I'm all ears!!!

Thanks for all your help.

The value of the Setting property itself has no Title property.

You need to apply Where before you extract the property value you need (as mentioned in the comments ):

$BlueSettings = $Import_Cfg |where {$_.Title -match "Blue"} |Select-Object -ExpandProperty Setting

or, using property enumeration:

$BlueSettings = ($Import_Cfg |where {$_.Title -match "Blue"}).Setting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM