在 PowerShell 中调用构造函数的 .NET 语法

.NET syntax for calling constructor in PowerShell

在 PowerShell 中使用 System.DirectoryServices.AccountManagement namespace, PrincipalContext class。我无法通过

呼叫PrincipalContext Constructor (ContextType, String)
[System.DirectoryServices.AccountManagement.PrincipalContext]::PrincipalContext($ContextType, $ContextName)

我收到错误 "Method invocation failed because [System.DirectoryServices.AccountManagement.PrincipalContext] does not contain a method named 'PrincipalContext'."

只能这样调用吗?

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

想了解为什么它以第二种方式工作而不是第一种方式。有没有办法用方括号做到这一点?

完整代码是这样的:

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

在 .net class 之后使用双冒号调用该 class 上的静态方法。

参见:Using Static Classes and Methods

使用以下语法:

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

您正试图在 PrincipalContext class 而不是构造函数上调用名为 PrincipalContext 的 static 方法。

Can it only be called the following way?

AFAIK,您需要使用 New-Object cmdlet 创建 class 的实例(调用构造函数)。

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?

第二种方法有效,因为您正确地创建了一个新对象并调用了构造函数。第一种方法不起作用,因为您没有调用构造函数 - 您正在尝试调用静态方法。