May 3rd, 2007

PowerShell Tricks – Trick 1

Powershell, by nazeeh.

Man I love Powershell! Finally there’s a shell on Windows that actually kicks major ass! I decided to start a series of Powershell tricks that I’ve learned. This one here is the first one :)

This first one is a simple piece of code in my profile.ps1 file that detects whether the shell is running as admin or not. If the shell is running as admin, it gets a red background to make that very clear:

To do that, edit your profile.ps1 file (or create it in a folder called WindowsPowershell in your Documents folder). The code I use to detect admin user or not is:

$wid=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp=new-object System.Security.Principal.WindowsPrincipal($wid)
$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
$IsAdmin=$prp.IsInRole($adm)
if ($IsAdmin)
{
  (get-host).UI.RawUI.Backgroundcolor="DarkRed"
  clear-host
}


This will cause the shell to have a DarkRed background if you’re admin, otherwise it will be the default blue color.

The $IsAdmin variable is then defined throughout the script, so you can use it for any other customization such as the prompt:

function prompt
{
    if ($IsAdmin)
    {
        Write-Host ("PS (Admin) " + $pwd +">") -nonewline -foregroundcolor Green
        $host.ui.rawui.WindowTitle = "Admin Shell: " + $(get-location)
    }
    else
    {
        Write-Host ("PS " + $pwd +">") -nonewline -foregroundcolor Green
        $host.ui.rawui.WindowTitle = "Windows Powershell: " + $(get-location)
    }
    return " "
}

That’s it! Have fun! More stuff to come soon.

Thanks for reading! I'd love to hear your thoughts, feel free to leave a comment below. Don't forget to subscribe to my RSS Feed!
Share and Enjoy:
  • Print
  • Digg
  • Twitter
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Back Top

Expose for Vista! VistaExpose PowerShell Tricks – Trick 2

Responses to “PowerShell Tricks – Trick 1”

  1. No comments yet.

Leave a Reply

Back Top