-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathAssert-ElevatedUser.ps1
53 lines (43 loc) · 1.36 KB
/
Assert-ElevatedUser.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
<#
.SYNOPSIS
Assert that the user has elevated the PowerShell session.
.DESCRIPTION
Assert that the user has elevated the PowerShell session. The command will
throw a statement-terminating error if the script is not run from an elevated
session.
.EXAMPLE
Assert-ElevatedUser
Throws an exception if the user has not elevated the PowerShell session.
.EXAMPLE
`Assert-ElevatedUser -ErrorAction 'Stop'`
This example stops the entire script if it is not run from an
elevated PowerShell session.
.OUTPUTS
None.
#>
function Assert-ElevatedUser
{
[CmdletBinding()]
param ()
$isElevated = $false
if ($IsMacOS -or $IsLinux)
{
$isElevated = (id -u) -eq 0
}
else
{
[Security.Principal.WindowsPrincipal] $user = [Security.Principal.WindowsIdentity]::GetCurrent()
$isElevated = $user.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if (-not $isElevated)
{
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
$script:localizedData.ElevatedUser_UserNotElevated,
'UserNotElevated',
[System.Management.Automation.ErrorCategory]::InvalidOperation,
'Command parameters'
)
)
}
}