.NET syntax for calling a constructor in PowerShell
Using the System.DirectoryServices.AccountManagement namespace , the PrincipalContext class in PowerShell. I cannot call PrincipalContext Constructor (ContextType, String)
through
[System.DirectoryServices.AccountManagement.PrincipalContext]::PrincipalContext($ContextType, $ContextName)
I get the error "Method invocation failed because [System.DirectoryServices.AccountManagement.PrincipalContext] does not contain a method named 'PrincipalContext'.
"
Can it be called only as follows?
New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ContextType, $ContextName
I would like to understand why it works in the second way, but not the first. Is there a way to do this with square brackets?
Complete code:
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')
source to share
Using double colon after the .net class is used to call a static method on that class.
See: Using static classes and methods
Using the syntax below:
[System.DirectoryServices.AccountManagement.PrincipalContext]::PrincipalContext($ContextType, $ContextName)
You are trying to call a static method named PrincipalContext in the PrincipalContext class instead of a constructor.
Can it be called only as follows?
AFAIK, you need to instantiate the class (call the constructor) using the New-Object cmdlet.
I would like to understand why it works in the second way, but not the first. Is there a way to do this with square brackets?
This works the second way because you are creating a new object correctly and calling the constructor. It doesn't work in the first way because you are not calling the constructor - you are trying to call a static method.
source to share