Powershell仅添加到阵列(如果不存在) [英] Powershell Only Add to Array if it doesn't exist
问题描述
在PowerShell v2中,我试图仅将唯一值添加到数组。我尝试使用一条if语句,粗略地讲,如果(如果不是(-不是$ Array-包含 SomeValue),则添加该值,但这仅在第一次时有效。我放了一个简单的代码段,显示了我正在执行的操作不起作用以及作为可行的解决方法所执行的操作。有人可以让我知道我的问题在哪里吗?
In PowerShell v2, I'm trying to add only unique values to an array. I've tried using an if statement that says, roughly, If (-not $Array -contains 'SomeValue'), then add the value, but this only ever works the first time. I've put a simple code snippet that shows what I'm doing that doesn't work and what I've done as a workaround that does work. Can someone please let me know where my issue is?
Clear-Host
$Words = @('Hello', 'World', 'Hello')
# This will not work
$IncorrectArray = @()
ForEach ($Word in $Words)
{
If (-not $IncorrectArray -contains $Word)
{
$IncorrectArray += $Word
}
}
Write-Host ('IncorrectArray Count: ' + $IncorrectArray.Length)
# This works as expected
$CorrectArray = @()
ForEach ($Word in $Words)
{
If ($CorrectArray -contains $Word)
{
}
Else
{
$CorrectArray += $Word
}
}
Write-Host ('CorrectArray Count: ' + $CorrectArray.Length)
第一个方法的结果是一个仅包含一个值的数组: Hello。第二种方法包含两个值: Hello和 世界。
The Result of the first method is an array containing only one value: "Hello". The second Method contains two values: "Hello" & "World". Any help is greatly appreciated.
推荐答案
要修复您的代码,请尝试 -notcontains
或至少用括号包裹您的包含测试。 Atm。您的测试结果为:
To fix your code, try -notcontains
or at least WRAP your contains-test in parantheses. Atm. your test reads:
如果 NOT array(如果数组不存在)包含单词。
If "NOT array"(if array doens't exist) contains word.
这没有道理。您想要的是:
This makes no sense. What you want is:
如果数组不包含单词。
If array does not contain word..
是这样写的:
If (-not ($IncorrectArray -contains $Word))
-notcontains
更好,因为@杜加斯建议。
-notcontains
is even better, as @dugas suggested.
这篇关于Powershell仅添加到阵列(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!