【发布时间】:2013-04-15 17:43:34
【问题描述】:
在 PowerShell v2 中,我尝试仅向数组添加唯一值。我尝试过使用 if 语句,粗略地说,如果(-not $Array -contains 'SomeValue'),然后添加该值,但这仅在第一次有效。我放了一个简单的代码 sn-p,它显示了我正在做的事情是行不通的,以及我所做的事情是一种行之有效的解决方法。有人可以告诉我我的问题在哪里吗?
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”和“World”。非常感谢任何帮助。
【问题讨论】:
标签: arrays powershell foreach contains