James O'Neill's Blog

July 23, 2008

PowerShell and checking management rights.

Filed under: Powershell,Virtualization,Windows Server,Windows Server 2008 — jamesone111 @ 5:59 am

Something which has come up more than once with the builds I of my PowerShell Hyper-V library has been that by default PowerShell doesn’t ask Windows to elevate it’s privileges – which, for example, the Microsoft Management Console does. By default it needs admin rights to see Virtual Machines and people running with an Account in the Administrators Group, but not the built in administrator account default to running non-elevated.

Now I wanted to test to see if an instance of PowerShell was running elevated or not, and I decided to do this by looking at something in the registry which only an privileged process can see; I picked the branch HKEY_USERS\S-1-5-20

Initially I wrote it it as  

Function test-Admin

{$Local:ErrorActionPreference = “SilentlyContinue”
new-psdrive -name HKUSERS -psp “registry” -root “HKEY_USERS” | out-null

dir  hkusers:\s-1-5-20 | out-null
($error[0].exception -notmatch ‘registry access’)

Remove-PSDrive hkusers | out-null

Many Powershell users know that there is a variable ErrorActionPreference , but not all of them realise that it can be scoped Just to a function. The next line Maps a “drive name” to the  “HKey_Users” branch of the registry , the function then tests to see if it is visible.

Now you may have noticed if you a DIR (or LS or get-child-item) that PowerShell shows what your looking at in the form Provider::Path so I was able to dispense with Add- and Remove- -psdrive and simply test as follows

Function test-Admin  
{ $Local:ErrorActionPreference = “SilentlyContinue”
dir Microsoft.PowerShell.Core\Registry::HKEY_USERS\S-1-5-20 | out-null

($error[0].exception -notmatch ‘registry access’)

It seems PowerShell will accept paths in this form anywhere , which is useful if you don’t want to create or rely on a drive.

This post originally appeared on my technet blog.


Create a free website or blog at WordPress.com.

%d bloggers like this: