我想在windows中获取本地用户帐户的组。如果我们从目录条目中获取本机对象,则可以完成此操作。这是通过API以下列方式实现的:
DirectoryEntry comp = new DirectoryEntry("WinNT://computername");
DirectoryEntry de = comp.Children.Find("account19", "user");
IADsUser NativeObject = (IADsUser)directoryentry.NativeObject;
但是如何通过PowerShell脚本获得同样的东西?
答案 0 :(得分:0)
您可以使用System.DirectoryServices.AccountManagement
namespace中的Microsoft .NET Framework类型来获取本地组成员身份。我编写了一个简单的PowerShell高级函数,它将检索本地用户帐户的组成员身份。
注意:因为我们在GetGroups()
method上使用UserPrincipal
class,所以此代码非常有效。您不需要获取所有组的列表,然后按照之前在评论中的建议迭代它们。
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;