Powershell Question Answered…

…by me. Thanks for nothing internet.

You may remember (but probably not) that I posted recently on the difference between two bits of powershell code that checked for whether or not I had administrator privileges on my PC. Well, through a happy accident I have discovered the difference.

The below snippet checks to see if I’m in the Admin role. It means nothing more than I can Admin things if I like.

function get-adminuser() {
   $id = [Security.Principal.WindowsIdentity]::GetCurrent()
   $p = New-Object Security.Principal.WindowsPrincipal($id)
   return $p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

This piece of code, on the other hand, is a wee bit more powerful. It actually looks to see if I have Admin rights currently. Much like the UNIX model, Windows XP and up allows you to be logged in as what UNIX would call a “user” versus “root.” This piece tells me my current role:

$strComputer = "."
$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$Group = $computer.psbase.children.find("Administrators")
$members= $Group.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}

$Host.UI.RawUI.WindowTitle = "Windows PowerShell - " + [Environment]::UserName
$found = $false
foreach($user in $members){
    if ($user =  [Environment]::UserName ) {
        $found = $true
    }
}
About these ads
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s