我可以使用以下方式读取用户帐户令牌:
[Security.Principal.WindowsIdentity]::GetCurrent()
然后获取该帐户所属的组。
如何读取计算机帐户令牌以获得组成员身份?
依赖于查询 Active Directory 的答案不是我想要的。
尝试过:
[Security.Principal.WindowsIdentity]::GetCurrent().DeviceClaims
但它是一个空集合。
我认为您可以使用
System.Security.Principal.WindowsIdentity
类和 System.DirectoryServices.AccountManagement
命名空间来执行此操作。因此,首先,我使用 WindowsIdentity.GetCurrent().User.Value
获取计算机的安全标识符(SID),然后,我为本地计算机创建一个 PrincipalContext
对象。这有助于我使用计算机的用户帐户和组,现在,我使用之前获得的 SID 找到计算机主体。这让我可以访问有关计算机的信息,最后,我使用 GetGroups()
获取计算机所属的组。然后我可以浏览每个组并显示他们的名字。
像这样的东西:
$computerSID = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$context = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine)
$computerPrincipal = [System.DirectoryServices.AccountManagement.ComputerPrincipal]::FindByIdentity($context, $computerSID)
$groups = $computerPrincipal.GetGroups()
foreach ($group in $groups) {
Write-Output $group.Name
}