completers/membershipSam.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$membershipSam = {
    param(
        $commandName,
        $parameterName,
        $wordToComplete,
        $commandAst,
        $fakeBoundParameter
    )

    $fakeBoundParameter.remove('identity')
    $filter = "{0}*" -f $wordToComplete

    $lFilter = "(&(|(objectClass=group)(objectClass=user))(samaccountname={0}*))" -f $wordToComplete

    Get-ADObject @fakeBoundParameter -LDAPFilter $lFilter | ForEach-Object {
        $obj = $_
        switch ($_.ObjectClass) {
            "group" { $obj | Get-ADGroup | Return-GroupObject }
            "user" { $obj | Get-ADUser | Return-UserObject }
        }
    }
}

# Enable for *-ADGroup*
Get-Command *-ADPrincipalGroupMembership | ForEach-Object {
    Register-ArgumentCompleter -CommandName $_ -Parameter Identity -ScriptBlock $membershipSam
}