(AD) in PowerShell

For me, this looks pretty weird:

$user1 = Get-ADUser sameuser
$user2 = Get-ADUser sameuser
$user1 -eq $user2                # -> false
# the same for groups:
$group1 = Get-ADGroup samegroup
$group2 = Get-ADGroup samegroup
$group1 -eq $group2              # -> false

In fact, it seems that Powershell users can be happy that 1 -eq 1this is true. Also:

"1" -eq 1           # -> true
@("1") -contains 1  # -> true

But:

$h1 = @{bla = 1}
$h2 = @{bla = 1}
$h1 -eq $h2                          # -> false
$h1.GetHashCode(), $h2.GetHashCode() # -> 60847006, 5156994
# the above return values of course vary
$a1 = @(1;2;3)
$a2 = @(1;2;3)
$a1.GetHashCode(), $a2.GetHashCode() # -> 52954848, 34157931
# surprise, surprise:
$a1 -eq $a2           # no return value at all? (tested with versions 4.0 and 5.1)
($a1 -eq $a2).GetType()              # or an Array?
($a1 -eq $a2).count                  # -> 0

Besides these fun behaviors that are really frustrating, I can't just like that:

$ones      = Get-ADPrincipalGroupMembership one
$seconds   = Get-ADPrincipalGroupMembership second
$excl_ones = $ones | ? { $_ -notin $seconds }

But you need to do something like this:

$second_nms = $seconds | % name
$excl_ones = $ones | ? { $_.name -notin $second_nms }

Did I miss something?

+4
source share
1 answer

To understand some of the oddities you see, we need to take a step back and look at the big picture, namely, the PowerShell infrastructure is built on top of: .NET!

Object Equality in .NET

$user1 -eq $user2fails because $user1both $user2are two different objects, although both can represent the same object in Active Directory.

.NET, .

, , [int], , , :

$a = 1
$b = 1
$a.Equals($b) # $true

- , , , , :

$a = New-Object object
$b = New-Object object
$a.Equals($b) # $false

, , $a $b , [object] .

GetHashCode() (, ) Equals() (, ), , , -, - [string] :

$a = "test"
$b = "test"
$a.Equals($b)

ADEntity ( ActiveDirectory) - , , .

PowerShell

, , :

$a1 = @(1;2;3)
$a2 = @(1;2;3)
$a1 -eq $a2 # NOTHING! WHAT GOING ON HERE?

, , PowerShell!

(-eq, -ne, -gt, -like, -match ..) : .

, : $true $false.

( ) , ( ) .

, :

$names  = "James","Jane","John"
$prefix = "Ja"

$names -like "$prefix*"

, -like - James Jane.

@(1;2;3) - eq @(1;2;3)

, - , (1 -eq @(1;2;3), 2 -eq @(1;2;3) ..) $true


. Active Directory , , - objectGUID. A GUID .NET - , :

$ones      = Get-ADPrincipalGroupMembership one
$seconds   = Get-ADPrincipalGroupMembership second
$excl_ones = $ones | ? { $_.objectGUID -notin $seconds.objectGUID }

(, , ..) , , objectSID - .

+8

Source: https://habr.com/ru/post/1693797/


All Articles