Search code examples
windowspowershellprofileelevated-privileges

What's the technique for loading a different powershell profile when running an elevated session


If I start an elevated powershell session there are some things I would like to include in my profile, such as connecting to mapped network drives, and as a bonus changing the colour of the prompt to remind me of my awesome elevated powers.

If I create a module with #Requires -RunAsAdministrator at the front of it, and then add this line to my profile.ps1 file

  Import-Module ($PSScripts + "elevated.ps1");

it does the job fine for elevated sessions, but every time I open a normal session I get a big red error message, which is somewhat less than optimal.

Import-Module : The script 'elevated.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows
PowerShell session is not running as Administrator. Start Windows PowerShell by  using the Run as Administrator option, and then try running the script again.
At C:\Users\sdixon.MV\Documents\WindowsPowerShell\profile.ps1:22 char:3
+   Import-Module ($PSScripts + "elevated.ps1") -ErrorAction silentlyco ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (elevated.ps1:String) [Import-Module], ScriptRequiresException
    + FullyQualifiedErrorId : ScriptRequiresElevation,Microsoft.PowerShell.Commands.ImportModuleCommand

this happens even if I try using:

  Import-Module ($PSScripts + "elevated.ps1") -ErrorAction silentlycontinue;

Is there a way of detecting whether the current session is elevated or not?


Solution

  • It looks like you can check for Administrator rights as follows:

    If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
        Import-Module ($PSScripts + "elevated.ps1")
    } Else {
        Write-Warning 'You do not currently have Administrator rights.'
    }
    

    Source: https://blogs.technet.microsoft.com/heyscriptingguy/2011/05/11/check-for-admin-credentials-in-a-powershell-script/

    He also wrote a Test-IsAdmin function, available in the Script Gallery here: https://gallery.technet.microsoft.com/scriptcenter/1b5df952-9e10-470f-ad7c-dc2bdc2ac946