我希望能够直接检索我的设备和嵌套组令牌,这可以通过安装ActiveDirectory模块轻松实现,但并不是我所有的设备都有此功能,我不希望安装它.

下面使用的是工作正常的ActiveDirectory模块.

$computer = Get-ADComputer -Identity "machinename"
$tokenGroups = (Get-ADObject -Identity $computer.DistinguishedName -Properties "tokenGroups").tokenGroups

$groupNames = $tokenGroups | ForEach-Object {
    $sid = New-Object System.Security.Principal.SecurityIdentifier $_
    $group = $sid.Translate([System.Security.Principal.NTAccount])
    $group.Value
}

$groupNames

这是一个不使用ActiveDirectory模块但针对用户的示例:

$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$groups = $currentUser.Groups

$groupNames = $groups | ForEach-Object {
    $_.Translate([System.Security.Principal.NTAccount])
}

$groupNames

如何为同时具有直接和嵌套组成员身份的计算机执行此操作?我曾想过导入ActiveDirectory模块使用的.dll,而不是安装,但我想看看是否有更干净的方法来做到这一点.

推荐答案

您可以使用DirectorySearcher instance(可通过PowerShell类型加速器[adsisearcher]访问的类型)-此API包含在.NET框架中,因此即使在未安装RSAT工具的计算机上也可以使用.

# Create a searcher that specifically searches for its own account object
$searcher = [adsisearcher]"(&(objectCategory=computer)(sAMAccountName=${Env:COMPUTERNAME}$))"

# Find computer account object 
if ($null -ne ($computer = $searcher.FindOne())) {
    # re-bind and fetch the computed token groups from the server
    $directoryEntry = $computer.GetDirectoryEntry()
    $directoryEntry.RefreshCache(@('tokenGroups'))

    # now we can access and parse the values
    foreach ($tokenGroupBuffer in $directoryEntry.Properties['tokenGroups']) {
        $SID = [System.Security.Principal.SecurityIdentifier]::new($tokenGroupBuffer,0)
        $SID.Translate([System.Security.Principal.NTAccount])
    }
}

.net相关问答推荐

将多行参数传递给Power Shell中的DotNet Pack命令

CLR如何在后台优化布尔比较操作?

如何在dotnet中使用OpenTelemetry Prometheus导出器导出多个版本的度量?

正则表达式匹配 URL 中的多个子目录

在.NET C#中截断整个单词的字符串

无法解析此引用.找不到程序集

什么是表达式树,如何使用它们,为什么要使用它们?

如何中止任务,如中止线程(Thread.Abort 方法)?

是否可以模拟 .NET HttpWebResponse?

为什么我得到 411 Length required 错误?

处理序列没有元素异常

如何将 UI Dispatcher 传递给 ViewModel

InternalsVisibleTo 属性不起作用

C# - 你如何停止计时器?

在 .NET Core 中在 MVC 之外使用 Razor

如何从头开始以编程方式配置 log4net(无配置)

IEnumerable vs IReadonlyCollection vs ReadonlyCollection 用于公开列表成员

SqlBulkCopy 的推荐批量大小是多少?

在 Windows 窗体 C# 应用程序中拥有配置文件的最简单方法

嵌套捕获组如何在正则表达式中编号?