-
Notifications
You must be signed in to change notification settings - Fork 1
/
Get-NameFromSID.ps1
80 lines (75 loc) · 2.52 KB
/
Get-NameFromSID.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function Get-NameFromSID {
<#
@AUTHOR: Bret McDanel
.SYNOPSIS
Resolves a SID into a username
.DESCRIPTION
Resolves a SID into a username
.PARAMETER SID
The SID to resolve
.OUTPUTS
PSCustomObject that contains account properties
.EXAMPLE
PS> Get-NameFromSID S-1-5-19
NTAccount Domain Username SID
--------- ------ -------- ---
NT AUTHORITY\LOCAL SERVICE NT AUTHORITY LOCAL SERVICE S-1-5-19
#>
[cmdletbinding()]
[OutputType("PSCustomObject", ParameterSetName = "ResolvedSID")]
Param(
[Parameter(
Position = 0,
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
HelpMessage = "Enter a SID string."
)]
[ValidateScript({
if ($_ -match 'S-1-[1235]-\d{1,2}(-\d+)*') {
$true
}
else {
Throw "The parameter value does not match the pattern for a valid SID."
$false
}
})]
[string]$SID
)
Begin {
Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($myinvocation.mycommand)"
} #begin
Process {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Converting $SID "
Try {
if ($SID -eq 'S-1-5-32') {
#apparently you can't resolve the builtin account
$resolved = "$env:COMPUTERNAME\BUILTIN"
}
else {
$resolved = [System.Security.Principal.SecurityIdentifier]::new($sid).Translate([system.security.principal.NTAccount]).value
}
if ($resolved -match "\\") {
$domain = $resolved.Split("\")[0]
$username = $resolved.Split("\")[1]
}
else {
$domain = $Null
$username = $resolved
}
[PSCustomObject]@{
PSTypename = "ResolvedSID"
NTAccount = $resolved
Domain = $domain
Username = $username
SID = $SID
}
}
Catch {
Write-Warning "Failed to resolve $SID. $($_.Exception.InnerException.Message)"
}
} #process
End {
Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($myinvocation.mycommand)"
} #end
} #close Resolve-SID