[英]Conditionally change boolean variable in an imported CSV
I am working on a script and I want to compare an array to another array, and change a boolean value (from $false to $true) based on a result. 我正在编写脚本,我想将一个数组与另一个数组进行比较,并根据结果更改一个布尔值(从$ false到$ true)。 This works fine on strings using the Replace method, but that doesn't exist for boolean values. 使用Replace方法在字符串上工作正常,但是对于布尔值不存在。 Can anyone tell me how to do this? 谁能告诉我该怎么做?
$bv
is an array of objects, as follows. $bv
是对象的数组,如下所示。
ServerName,Domain,Environment,Tier0
ServerA,usa,dev,$false
ServerB,usa,sit,$false
I am trying to compare that list to another list of Tier0
computers ( $t0List
) that looks like this. 我正在尝试将该列表与另一个Tier0
计算机列表( $t0List
)进行比较。
ServerB ServerC ServerD
So if there is a match between the ServerName in column 1 of $bv
and an entry in $t0List
, then I want to change the Tier0
column in $bv
to $true
. 因此,如果在$bv
1列中的ServerName和$t0List
一个条目之间存在匹配项,那么我想将$bv
的Tier0
列更改为$true
。
foreach ($b in $bv) {
if ($t0List -contains $b.ServerName) {
$b.Tier0.Replace($b.Tier0,$true)
}
}
The error I get with the above code is... 我收到以上代码的错误是...
Method invocation failed because [System.Boolean] does not contain a method named 'Replace'.
There's no need to use something like replace, just assign the value with =
: 无需使用诸如replace之类的东西,只需使用=
分配值即可:
foreach ($b in $bv) {
if ($t0List -contains $b.ServerName) {
$b.Tier0 = $true
}
}
Want to simplify it even more? 是否想进一步简化? Just assign it the result of your -contains
: 只需为其分配-contains
的结果即可:
foreach ($b in $bv) {
$b.Tier0 = $t0List -contains $b.ServerName
}
Maybe this helps you: 也许这可以帮助您:
You can flip between $true
and $false
just by telling it -not
to be 您可以翻转之间$true
和$false
只需告诉它-not
是
-not $true
brings back $false
-not $true
会带来$false
-not $false
brings back $true
-not $false
带回$true
So 所以
foreach ($b in $bv) {
if ($t0List -contains $b.ServerName) {
$b.Tier0 = -not ($b.Tier0)
}
}
or 要么
foreach ($b in $bv) {
if ($t0List -contains $b.ServerName) {
$b.Tier0 = $true
}
}
should work 应该管用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.