使用powershell更新重复数组的字段值



下面是我的输入数组

Store,hotel,cafe,bar, number
111,true, true, true,02
111, false, false, true,09
112, true, false,true,08
112, true, false,false,06
113, true, false, true,05

预期输出

Store, hotel,cafe,bar, number
111, true, true, true, 02
111, true, true, true,09
112, true, false, true, 08
112, true, false, true, 06
113, true, false, true,05

我的代码
$testarray = import-csv -path "C:directoryocb2021preprocessings.csv"
foreach($member in $testarray)
{
if(($testarray -match $member.store).count -gt 1)
{
write-host  "match found"
$success = $member.store | where $member.bar -eq 'true'
}
}

不清楚您想要做什么,但是您的代码中存在一些基本问题:

  1. 您没有将$Success初始化为$false,如果您在相同的powershell会话中使用不同的输入多次运行该脚本,只要一次成功,所有将返回成功。Powershell变量是为会话而存在的,而不仅仅是为脚本的运行而存在。然而,我不确定这个变量是否适合你的目标。
  2. 美元成员。Store是$Member对象的Store属性,然后将其管道化并检查$Member。然而,这并没有做你所期望的,它正在取美元的成员。并使用它作为属性name所以实际上它在寻找"商店"(字符串)有一个名为true或false的属性(取决于行),然后确定该属性是真还是假。
  3. 将返回对象因此,$Success要么是对象,要么是null,而不是true/false。在某些地方,这可以隐式地处理为真/假(例如if),但如果你试图将其强制转换为null,它可能会失败,因为你不能将某些对象强制转换为bool。
  4. 你没有对$member的任何属性做任何赋值,所以你的输出永远不会改变

你似乎想做这样的事情:

$testarray = import-csv -path "C:directoryocb2021preprocessings.csv"
$Success=$false
# loop each object
foreach($member in $testarray)
{
#matching condition
if(($testarray -match $member.store).count -gt 1)
{
write-host  "match found"
#indicate we had at least one match
$Success=$true
#change the value of the property "bar"
$member.bar = $true
}
}
if ($Success) {
write-Host 'At least one match was found' -f Green
} else {
write-host 'No matches were found!' -f Red
}
write-output $TestArray 

最新更新