2015-04-27 27 views
3

在PowerShell中使用System.DirectoryServices.AccountManagement命名空间,PrincipalContext类。我无法通过在PowerShell中调用构造函数的.NET语法

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

我得到错误调用PrincipalContext Constructor (ContextType, String)"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') 

回答

4

在.NET类之后使用双冒号来调用该类的静态方法。

参见:Using Static Classes and Methods

使用下面的语法:

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

您试图呼吁PrincipalContext类而不是构造函数命名PrincipalContext一个静态方法。

它只能被称为以下方式吗?

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

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

它工作的第二种方式,因为你正确地创建一个新的对象并调用构造函数。它不起作用的第一种方式,因为你没有调用构造函数 - 你正试图调用一个静态方法。

+0

请放下它。在这种情况下,我不知道这对我意味着什么。 –

+0

@Entbark - 我扩大了我的原始答案。 – dugas

+1

对于那些发现这种情况的人来说,在Powershell v5.1(甚至可能是5.0--但不是之前)类中,可以使用方括号表示法中的构造函数。这使Powershell ISE可以使用Intellisense作为构造函数签名。像这样调用:'[System.DirectoryServices.AccountManagement.PrincipalContext] :: new($ ContextType,$ ContextName)''。 –

相关问题