【问题标题】:How can I convert a SID to an account name in PowerShell?如何在 PowerShell 中将 SID 转换为帐户名?
【发布时间】:2014-03-11 17:06:21
【问题描述】:

这个问题的灵感来自 this similar question 使用 C# 标记。如果我有一个 Windows SID,并且想将其转换为可读的帐户名称,如何使用 PowerShell 而不是 C# 来实现这一点?

现在,我有以下代码,用于检索当前登录用户帐户的组成员身份:

$Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$Identity.Groups;

Groups 属性的结果没有给我任何帐户名称,只有 SID。如果我将Groups 属性的输出通过管道传输到PowerShell 的Get-Member cmdlet,我可以看到生成的对象是System.Security.Principal.SecurityIdentifier 对象。但是,查看 the documentation(和 Intellisense)的 Groups 属性表明它正在返回一个 IdentityReferenceCollection 对象。

如何将这些SecurityIdentifier 对象转换为专有名称?

【问题讨论】:

    标签: .net security powershell


    【解决方案1】:

    将 SID 解析为帐户名称的一种方法是使用 Win32_SID 类:

    PS C:\> $sid = 'S-1-5-18'
    PS C:\> [wmi]"Win32_SID.SID='$sid'"
    
    
    __GENUS              : 2
    __CLASS              : Win32_SID
    __SUPERCLASS         :
    __DYNASTY            : Win32_SID
    __RELPATH            : Win32_SID.SID="S-1-5-18"
    __PROPERTY_COUNT     : 5
    __DERIVATION         : {}
    __SERVER             : CARBON
    __NAMESPACE          : root\cimv2
    __PATH               : \\CARBON\root\cimv2:Win32_SID.SID="S-1-5-18"
    AccountName          : SYSTEM
    BinaryRepresentation : {1, 1, 0, 0...}
    ReferencedDomainName : NT-AUTHORITY
    SID                  : S-1-5-18
    SidLength            : 12
    PSComputerName       : CARBON
    

    【讨论】:

    • 不错的选择。感谢发帖。
    【解决方案2】:

    解决方法是使用SecurityIdentifier classTranslate() method。此方法的单个参数是对要将 SecurityIdentifier 转换为的 .NET 类型的引用。如果您检查 this answer 到类似的 C# 问题,您会发现您可以简单地传递对 System.Security.Principal.NTAccount class 的引用。

    生成的代码如下所示:

    $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent();
    foreach ($Group in $Identity.Groups) {
        $Group.Translate([System.Security.Principal.NTAccount]).Value;
    }
    

    【讨论】:

      【解决方案3】:

      看起来你已经有了答案——我不久前写了一个包装器,它还搜索well known SIDs 的列表,如果它有帮助的话。 ConvertFrom-SID

      您可以将其提取出来的通用方法如下,其中 $sid 包含一个 SID 字符串:

      $sid = '<SIDGoesHere>';
      $objSID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $sid;
      $name = $objSID.Translate([System.Security.Principal.NTAccount]).Value;
      

      干杯!

      【讨论】:

      • 只是在 SO 上记录 :)
      • 链接作为补充信息可能会有所帮助,但强烈建议不要仅链接答案for these reasons。您应该在答案中包含代码(添加链接是可以的),否则这实际上更像是评论而不是答案。在当前形式下,您的帖子很有可能会被自动标记为低质量帖子审核队列并被删除。
      • @CookieMonster:只是想提醒您,即使您的New-Object 语法在技术上有效,但它具有欺骗性,因为它看起来像 C# 代码,而 PowerShell 绝对不是。我进行了编辑,以便在 PowerShell 语法中更清楚地拼写出来。
      猜你喜欢
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2011-08-16
      • 1970-01-01
      相关资源
      最近更新 更多