Self Elevating PowerShell cmdlet

Sometimes you need to run a script as an administrator. It’s a simple enough process to start an Administrator PowerShell window, but you still need to navigate to the path required etc etc. Since there isn’t a simple sudo command for PowerShell one way to handle the permissions is to use a self-elevating script.

[code language=”powershell”]
$Principal = New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$AdminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
if (-not $Principal.IsInRole($AdminRole)) {
Start-Process -FilePath powershell -ArgumentList $MyInvocation.MyCommand.Definition -Verb runas
exit
}
# add code here
[/code]

This will check if the executing user has the Administrators role and if not start an elevated process. This will trigger a UAC prompt. As such, it will not work in automated scripts – they will hang waiting for the user input.

The magic of this snippet is use the of $MyInvocation.MyCommand.Definition. This property includes a string representation of the currently executing function. $MyInvocation is an interesting variable and I would recommend reading up on it – there are many useful properties exposed.