2012-03-22 44 views
10

所以我們可以說我有這個數組:在Powershell中,如何檢查一個數組中的所有項是否存在於第二個數組中?

$requiredFruit= @("apple","pear","nectarine","grape") 

而且我有第二個陣列稱爲$fruitIHave。我如何檢查$fruitIHave是否有$requiredFruit中的所有內容。只要$requiredFruit中的所有內容都存在,$fruitIHave中是否有更多項目並不重要。

我知道我可以迭代列表,但這似乎效率低下,有沒有一個內置的方法來做到這一點?

回答

24

你嘗試比較,對象:

$requiredFruit= @("apple","pear","nectarine","grape") 
$HaveFruit= @("apple","pin","nectarine","grape") 
Compare-Object $requiredFruit $haveFruit 
InputObject             SideIndicator 
-----------             ------------- 
pin               => 
pear              <= 

Compare-Object $requiredFruit $haveFruit | where {$_.sideindicator -eq "<="} | % {$_.inputobject} 
pear 
1

不正是 「內置」,而是:

[regex] $RF_regex = ‘(?i)^(‘ + (($requiredFruit |foreach {[regex]::escape($_)}) –join 「|」) + ‘)$’ 

($fruitIHave -match $RF_regex).count -eq $requiredFruit.count 

這就產生了從$ requiredFruit的元素交替的正則表達式。與$ fruitIHave匹配,它將返回所有匹配的項目。如果$ fruitIhave可能具有相同水果的重複項,則可能需要在計數之前通過get-unique運行匹配結果。它可能比遍歷列表中的單個比較要慢,但是一旦你構建了正則表達式,它將非常有效地進行重複匹配。

0

無論如何,你將不得不遍歷一個或兩個數組。這裏是一個班輪方法:

$hasAllRequiredFruit = ($requiredFruit | Where-Object { $fruitIHave -contains $_ }).Length -eq $requiredFruit.Length; 

一個foreach循環會更好,因爲你可以爲你找到所需的水果,缺少儘快停止迭代:

$hasAllRequiredFruit = $true; 
foreach ($f in $requiredFruit) 
{ 
    if ($fruitIHave -notcontains $f) 
    { 
     $hasAllRequiredFruit = $false; 

     break; 
    } 
} 
+1

@匿名懦夫:爲什麼downvote? – BACON 2016-01-15 18:22:42

11

如果你有數組:

$requiredFruit= @("apple","pear","nectarine","grape") 
$someFruit= @("apple","banana","pear","nectarine","orange","grape") 
$moreFruit= @("apple","banana","nectarine","grape") 

你可以得到一個布爾結果:

'Check $someFruit for $requiredFruit' 
-not @($requiredFruit| where {$someFruit -notcontains $_}).Count 

'Check $moreFruit for $requiredFruit' 
-not @($requiredFruit| where {$moreFruit -notcontains $_}).Count 

使用計數的數組防止單個值不匹配計算結果爲假。例如:

# Incorrect result 
-not (0| where {(1,2) -notcontains $_}) 

# Correct result 
-not @(0| where {(1,2) -notcontains $_}).Count 

使用PowerShell v3,則可以使用select -first 1停止管道時,第一發現不匹配(在V2 select -first 1只允許一個通過對象,但管道的前面元素繼續處理)。

-not @($requiredFruit| where {$moreFruit -notcontains $_}| select -first 1).Count 
相關問題