4

Using the System.DirectoryServices.AccountManagement namespace, PrincipalContext class in PowerShell. I am unable to call PrincipalContext Constructor (ContextType, String) via

[System.DirectoryServices.AccountManagement.PrincipalContext]::PrincipalContext($ContextType, $ContextName)

I get error "Method invocation failed because [System.DirectoryServices.AccountManagement.PrincipalContext] does not contain a method named 'PrincipalContext'."

Can it only be called the following way?

New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ContextType, $ContextName

Would like to understand why it works the second way but not the first way. Is there a way to do this with square brackets?

Full code is this:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ContextName = $env:COMPUTERNAME
$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$PrincipalContext = [System.DirectoryServices.AccountManagement.PrincipalContext]::PrincipalContext($ContextType, $ContextName)
$IdentityType = [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName
[System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($PrincipalContext, $IdentityType, 'Administrators')
Benjamin Hubbard
  • 2,797
  • 22
  • 28

1 Answers1

5

Using the double colon after a .net class is used to call a static method on that class.

See: Using Static Classes and Methods

Using the below syntax:

[System.DirectoryServices.AccountManagement.PrincipalContext]::PrincipalContext($ContextType, $ContextName)

You are trying to call a static method named PrincipalContext on the PrincipalContext class instead of the constructor.

Can it only be called the following way?

AFAIK, you need to create the instance of the class (call the constructor) using the New-Object cmdlet.

Would like to understand why it works the second way but not the first way. Is there a way to do this with square brackets?

It works the second way because you are correctly creating a new object and calling the constructor. It doesn't work the first way because you are not calling the constructor - you are attempting to call a static method.

dugas
  • 12,025
  • 3
  • 45
  • 51
  • Please dumb it down. I don't really know what that should mean to me in this context. – Benjamin Hubbard Apr 27 '15 at 15:59
  • @Entbark - I expanded my original answer. – dugas Apr 27 '15 at 16:18
  • 5
    For those finding this, in Powershell v5.1 (maybe even 5.0 - but not before) classes have the constructors available from the square brackets notation.This alows Powershell ISE to use Intellisense for the constructor signatures. Called like so: `[System.DirectoryServices.AccountManagement.PrincipalContext]::new($ContextType, $ContextName)`. – Petru Zaharia Aug 09 '17 at 19:38