0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellで2つのリストの差分を取得するにはnotin演算子が便利

Posted at

はじめに

2つのデータリストのうち一方のリストに含まれていてもう一方に含まれていないデータをPowerShellで取得するにはnotin演算子を利用すると便利である。

例えば、実際にはあまりないパターンかもしれないが、Office 365でGet-MsolUserの取得結果に含まれるがGet-Mailboxの取得結果には含まれないオブジェクトを抽出したリストを取得するには以下のようにすればよい。
この場合は両リストに備わっているUserPrincipalName属性がキーとなる。

$ExOMBXs = Get-Mailbox -ResultSize Unlimited
Get-MsolUser -All | Where-Object {$_.UserPrincipalName -notin ($ExOMBXs).UserPrincipalName}

参考までに、同じことをForEach-Objectですごく丁寧にしようとすると以下のようになる。

$ExOMBXs = Get-Mailbox -ResultSize Unlimited
$Datas = New-Object System.Collections.ArrayList

Get-MsolUser -All | ForEach-Object {

    $UPN = $_.UserPrincipalName
    $ExOMBX = $ExOMBXs | Where-Object {
        $_.UserPrincipalName -eq $UPN
    }

    if($null -eq $ExOMBX){
        [void]$Datas.Add($_)
    }

}

$Datas

おわりに

今までは上記の後者の方法しか知らず、複雑なスクリプトが書けるオレSUGEEE!していた過去の自分をはたきたい。

以上

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?