简体   繁体   English

Powershell命令不起作用的地方

[英]Powershell Where command not working

I have a text file that contains elements separated by an '=' sign (ie color1=red, color2=blue, etc. 我有一个文本文件,其中包含用'='符号分隔的元素(即color1 = red,color2 = blue等。

I used the import-csv command and provide headers (ie 我使用了import-csv命令并提供标题(即

$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). 当我输入$ Import_cfg时,我可以看到整个数组(没有“ =”符号)。 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. 请不要大惊小怪为什么我要使用import-csv和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. Setting属性本身的值没有Title属性。

You need to apply Where before you extract the property value you need (as mentioned in the comments ): 您需要提取所需的属性值之前应用到Where (如注释中所述 ):

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

or, using property enumeration: 或者,使用属性枚举:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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