【问题标题】:How to get the IADSUser native object from directory entry through powershell?如何通过powershell从目录条目中获取IADSUser本机对象?
【发布时间】:2014-02-13 15:19:26
【问题描述】:

我想在 windows 中获取本地用户帐户的组。如果我们从目录条目中获取本机对象,则可以做到这一点。这是通过 API 以下列方式实现的:

DirectoryEntry comp = new DirectoryEntry("WinNT://computername");
DirectoryEntry de = comp.Children.Find("account19", "user");     
IADsUser NativeObject = (IADsUser)directoryentry.NativeObject;

但是如何通过powershell脚本得到同样的东西呢?

【问题讨论】:

  • 嗯.. 也许在 powershell 中还有另一种方法可以使用[ADSI] 完成域/本地用户的任务。你能告诉NativeObject你的最终目标是什么吗?
  • 获取用户的组。一种方法是获取所有组。然后他们的成员并检查用户是否属于该组。但这效率不高。
  • 这应该会有所帮助:stackoverflow.com/questions/4548476/…

标签: windows powershell com directoryentry


【解决方案1】:

您可以使用System.DirectoryServices.AccountManagement namespace 中的Microsoft .NET Framework 类型来获取本地组成员资格。我编写了一个简单的 PowerShell 高级函数,它将检索本地用户帐户的组成员身份。

注意:因为我们在UserPrincipal class上使用了GetGroups() method,所以这段代码效率很高。您确实不需要需要获取所有组的列表,然后迭代它们,正如之前在 cmets 中所建议的那样。

function Get-LocalUserGroupMembership {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [string] $Identity = $env:USERNAME
    )

    # Import the System.DirectoryServices.AccountManagement .NET library
    Add-Type -AssemblyName System.DirectoryServices.AccountManagement;

    # Get a reference to the local machine's Security Account Manager (SAM)
    $PrincipalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Machine);
    # Get a reference to a specific user principal, based on its account name
    $UserAccount = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($PrincipalContext, $Identity);
    if (!$UserAccount) {
        throw 'User account could not be found!';
    }

    # Call the GetGroups() method on the UserPrincipal object
    $GroupList = $UserAccount.GetGroups();

    # Output the list of groups
    Write-Output -InputObject $GroupList;
}

Get-LocalUserGroupMembership;

【讨论】:

  • 我尝试了上面的脚本。我得到以下异常:“未处理的异常:System.Management.Automation.RemoteException:找不到用户帐户!”
猜你喜欢
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 2015-07-10
相关资源
最近更新 更多