Используя это в PowerShell, вы получите WindowsIdentity себя в PowerShell.
[System.Security.Principal.WindowsIdentity]::GetCurrent()
Это будет содержать следующих участников
TypeName: System.Security.Principal.WindowsIdentity
Name MemberType Definition
---- ---------- ----------
AddClaim Method void AddClaim(System.Security.Claims.Claim claim)
AddClaims Method void AddClaims(System.Collections.Generic.IEnumerable[System.Security.Claims.Claim] cl...
Clone Method System.Security.Claims.ClaimsIdentity Clone()
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
FindAll Method System.Collections.Generic.IEnumerable[System.Security.Claims.Claim] FindAll(System.Pr...
FindFirst Method System.Security.Claims.Claim FindFirst(System.Predicate[System.Security.Claims.Claim] ...
GetHashCode Method int GetHashCode()
GetObjectData Method void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, ...
GetType Method type GetType()
HasClaim Method bool HasClaim(System.Predicate[System.Security.Claims.Claim] match), bool HasClaim(str...
Impersonate Method System.Security.Principal.WindowsImpersonationContext Impersonate()
OnDeserialization Method void IDeserializationCallback.OnDeserialization(System.Object sender)
RemoveClaim Method void RemoveClaim(System.Security.Claims.Claim claim)
ToString Method string ToString()
TryRemoveClaim Method bool TryRemoveClaim(System.Security.Claims.Claim claim)
WriteTo Method void WriteTo(System.IO.BinaryWriter writer)
AccessToken Property Microsoft.Win32.SafeHandles.SafeAccessTokenHandle AccessToken {get;}
Actor Property System.Security.Claims.ClaimsIdentity Actor {get;set;}
AuthenticationType Property string AuthenticationType {get;}
BootstrapContext Property System.Object BootstrapContext {get;set;}
Claims Property System.Collections.Generic.IEnumerable[System.Security.Claims.Claim] Claims {get;}
DeviceClaims Property System.Collections.Generic.IEnumerable[System.Security.Claims.Claim] DeviceClaims {get;}
Groups Property System.Security.Principal.IdentityReferenceCollection Groups {get;}
ImpersonationLevel Property System.Security.Principal.TokenImpersonationLevel ImpersonationLevel {get;}
IsAnonymous Property bool IsAnonymous {get;}
IsAuthenticated Property bool IsAuthenticated {get;}
IsGuest Property bool IsGuest {get;}
IsSystem Property bool IsSystem {get;}
Label Property string Label {get;set;}
Name Property string Name {get;}
NameClaimType Property string NameClaimType {get;}
Owner Property System.Security.Principal.SecurityIdentifier Owner {get;}
RoleClaimType Property string RoleClaimType {get;}
Token Property System.IntPtr Token {get;}
User Property System.Security.Principal.SecurityIdentifier User {get;}
UserClaims Property System.Collections.Generic.IEnumerable[System.Security.Claims.Claim] UserClaims {get;}
Но как мне получить WindowsIdentity для SID известного пользователя?
Я попытался создать и использовать SecurityIdentifier, как показано ниже, но это выдает ошибку.
$Sid = 'ENTER SID HERE'
$SecurityIdentifier = [System.Security.Principal.SecurityIdentifier]$Sid
$WindowsIdentity = New-Object System.Security.Principal.WindowsIdentity $SecurityIdentifier
Новый объект: исключение при вызове «.ctor» с аргументами «1»: «Указанное имя не является правильно сформированным именем учетной записи. "
Я также пробовал использовать приведение типов, [System.Security.Principal.WindowsIdentity]$SecurityIdentifier, но командлет New-Object дал несколько лучшее описание ошибки.
В другом месте мне было предложено, что Как получить учетную запись NT из SID с помощью PowerShell является дубликатом этого вопроса. Но этот ответ возвращает объект NTAccount, который содержит только следующие члены.
TypeName: System.Security.Principal.NTAccount
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object o)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
IsValidTargetType Method bool IsValidTargetType(type targetType)
ToString Method string ToString()
Translate Method System.Security.Principal.IdentityReference Translate(type targetType)
Value Property string Value {get;}
Мне нужен объект WindowsIdentity.





Я не уверен, почему вы так зациклены на этом конкретном типе объекта, но вы можете сделать это, если попытаетесь...
Преобразуйте строку SID в объект [System.Security.Principal.SecurityIdentifier] и используйте метод Translate(type targetType), чтобы сделать ее объектом NTAccount. Это дает вам фактическое имя и контекст для пользователя. Небольшая манипуляция со строкой преобразует domain\user в UserPrincipalName user@domain, и это все, что вам нужно для создания объекта WindowsIdentity.
Function Convert-SIDtoWindowsID {
[CmdletBinding()]
Param(
[parameter(ValueFromPipeline)]
[System.Security.Principal.SecurityIdentifier]$SID
)
$UPN=$SID.Translate([System.Security.Principal.NTAccount]) -replace '(.+?)\\(.+)','$2@$1'
[System.Security.Principal.WindowsIdentity]::new($UPN)
}
Тогда вы можете просто сделать:
Convert-SIDtoWindowsID 'S-1-5-21-1111111111-2222222222-3333333333-44444444'
Спасибо, но это решение работает только с учетными записями домена. Мне понадобится WindowsIdentity для локальной учетной записи, а у них нет свойства UPN.
Хороший ответ. Я бы еще добавил
ValueFromPipelineByPropertyName, чтобы вы могли прямо в него передатьGet-ADUser.