Benjamin Hubbard
Benjamin Hubbard

Reputation: 2917

.NET syntax for calling constructor in PowerShell

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')

Upvotes: 7

Views: 5015

Answers (1)

dugas
dugas

Reputation: 12443

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.

Upvotes: 6

Related Questions