forked from RamblingCookieMonster/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Test-ForAdmin.ps1
88 lines (71 loc) · 2.96 KB
/
Test-ForAdmin.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
81
82
83
84
85
86
87
88
function Test-ForAdmin {
<#
.SYNOPSIS
Test whether a specified user is in the administrator role
.DESCRIPTION
Test whether a specified user is in the administrator role
Note: Requires .NET 3.5 or later
.PARAMETER username
One or more usernames to test. Defaults to the current PowerShell user ($env:username)
.EXAMPLE
If(Test-ForAdmin){
"The current user is running with the administrator role"
}
Else{
"The current user is not running with the administrator role"
}
.EXAMPLE
#Test whether JohnDoe is an admin on this computer
Test-ForAdmin -username JohnDoe
.FUNCTIONALITY
Computers
#>
[cmdletbinding()]
param(
[Parameter(
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=0
)][string[]]$username =$env:username
)
Process{
foreach($user in $username){
#If username matches, don't query AD
if($user -eq $env:username){
write-verbose "Username parameter value matches username environment variable: Don't check AD"
$wid = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp = New-Object System.Security.Principal.WindowsPrincipal($wid)
$adm = [System.Security.Principal.WindowsBuiltInRole]::Administrator
$prp.IsInRole($adm)
}
else{
#At this point, the username is not $env:username. Work with AD.
Write-Verbose "Username parameter value does not match username environment variable: Check AD"
#Add the .net type
$type = 'System.DirectoryServices.AccountManagement'
Try{
Add-Type -AssemblyName $type -ErrorAction Stop
}
Catch {
Throw "Could not load $type`: Confirm .NET 3.5 or later is installed"
Break
}
#Look up user to get UPN
Try{
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$upn = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct,$user) | select -ExpandProperty UserPrincipalName
}
Catch{
Throw "Could not find user '$user': $_"
}
#Build WindowsIdentity with UPN
$wid = New-Object System.Security.Principal.WindowsIdentity($upn)
#Verify whether the account is an admin on the local machine
$prp = New-Object System.Security.Principal.WindowsPrincipal($wid)
$adm = [System.Security.Principal.WindowsBuiltInRole]::Administrator
$prp.IsInRole($adm)
}
}
}
}