gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:01:03 25 4
gpt4 key购买 nike

使用 System.DirectoryServices.AccountManagement命名空间,PrincipalContext PowerShell 中的类。我无法调用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 类之后使用双冒号用于调用该类的静态方法。

见:Using Static Classes and Methods

使用以下语法:

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

您正在尝试在 PrincipalContext 类而不是构造函数上调用名为 PrincipalContext 的静态方法。

Can it only be called the following way?



AFAIK,您需要使用 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?



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

关于在 PowerShell 中调用构造函数的 .NET 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29899955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com