English 中文(简体)
在 Powershell 2D 数组中查找缺失的行
原标题:Find missing rows in Powershell 2D arrays

我有两个阵列,每个阵列有两个字段(例如项目和价格)。

以下是我一个数组(实际上两个数组的结构相同)的获得成员结果。

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition                    
----        ----------   ----------                    
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()             
GetType     Method       type GetType()                
ToString    Method       string ToString()             
item        NoteProperty System.String field1=computer 
price       NoteProperty System.String field2=2000     

我需要在阵列$shoppA 中找到项目, 而在阵列$shoppB 中找不到项目。 我现在使用两个循环来查找丢失的项目 。

$missing = @()
foreach ($itemA in $shopA) {
  $found = 0
  foreach ($itemB in $shopB) {
    if ($itemB.item -eq $itemA.item) {
      $found = 1
    }
  }
  if ($found = 0) {
    $missing += $itemA
  }
}

这个方法对我有效,但我的2个阵列很大,我想要比整个阵列滚动速度更快的方法。 。 。 。

我一直在寻找更好的方法来做到这一点,比较对象几乎完成了这项工作,但所有例子似乎只对单一维数组起作用。

谢谢 谢谢

最佳回答

从我所看到的,你确实有两个1D阵列, 尽管你声称相反。

寻找失踪物品的天真方式将是

$missing = $shopA | ? { $x = $_; !($shopB | ? {$_.item -eq $x.item})}

然而,这总是O(n2),这样可以更快地从以下的$shopB 收集到所有物品:首先从一个可以快速收集到所有物品,这就使得可以检查O(1)的存在,而不是O(n)的存在:

$hash = @{}
$shopB | %{ $hash[$_.item] = 1 }
$missing = $shopA | ?{ !$hash.ContainsKey($_.item) }
问题回答

像这样吗?

 $shopA= @(1, 2, 3, 4)
 $shopB= @(4, 3, 5, 6)
 $shopB | where { $shopA -notcontains $_  }




相关问题
Mutually exclusive powershell parameters

SCENARIO I m writing a cmdlet for Powershell 2.0 using Visual Studio 2008 and .NET 3.5 the cmdlet requires 3 arguments. my intended grammar of the cmdlet is something like this: cmdletname [foo|...

Run a program from PowerShell with timeout

I ll write a script that runs a program and wait for it finished. But if the program is not finished within a specified time I want that the program is killed.

How to transpose data in powershell

I have a file that looks like this: a,1 b,2 c,3 a,4 b,5 c,6 (...repeat 1,000s of lines) How can I transpose it into this? a,b,c 1,2,3 4,5,6 Thanks

Powershell v2 remoting and delegation

I have installed Powershell V2 on 2 machines and run Enable-PsRemoting on both of them. Both machines are Win 2003 R2 and are joined to the same active directory domain and I can successfully run ...

PowerShell -match operator and multiple groups

I have the following log entry that I am processing in PowerShell I m trying to extract all the activity names and durations using the -match operator but I am only getting one match group back. I m ...

热门标签