Setting PowerShell console color when running elevated

Recently I’ve just started delving into Powershell and I’m really growing fond of it!

One tiny feature I missed about classic console (dare I say I miss it!) was how the console foreground color changed to yellow when you are running in elevated mode (through Run As Administrator).

Then I stumbled onto the creation of a personal profile.ps1 file inside your <Profile Documents>\WindowsPowerShell\profile.ps1. First things first, be sure that you’ve run Set-ExecutionPolicy to either RemoteSigned or Unrestricted (ironically, in Vista be sure that you’re elevated with Run as Administrator). Next up create the WindowsPowerShell folder in your user profile’s My Documents (or Documents in Vista) and create a new text file in there called profile.ps1.

Using code borrowed and ever so slightly changed from Nivot Ink you can add the following to your profile file:

  1. # Returns a boolean indicating whether the passed windows identity is an administrator.  
  2. # Argument defaults to current user.  
  3. function Test-Elevated {  
  4.   param(  
  5.     $identity = [security.principal.windowsidentity]::Getcurrent()  
  6.   )  
  8.   $principal = new-object  security.principal.windowsprincipal $identity;  
  9.   $adminsRole =  []“S-1-5-32-544”;  
  10.   $principal.IsInRole($adminsRole);  
  11. }  
  13. # Usage:     
  14. #     
  15. # If-Elevated { .. admin code .. } { “sorry, need admin” }      
  16. #     
  17. function If-Elevated {     
  18.   param(     
  19.     [scriptblock]$AsAdmin = $(Throw “Missing ‘as admin’ script”),     
  20.     [scriptblock]$AsUser= $(Throw “Missing ‘as user’ script”)     
  21.   )     
  23.   if (Test-Elevated) {     
  24.     & $AsAdmin    
  25.   } else {     
  26.     & $AsUser    
  27.   }     
  28. }  
  30. # Change the foreground color to yellow if admin  
  31. If-Elevated { [System.Console]::ForegroundColor = [System.ConsoleColor]::Yellow; } { }  

Remember PowerShell has all of .NET at it’s disposal so that’s exactly what we’re using in the Test-Elevated function. Similarly we change the console colour in the same way we would in a normal console application and while there we’ll also keep the current working directory consistent to the $HOME variable (in elevated mode it defaults to the Windows\System32 directory).

The proof in the pudding:



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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