powershellimport-module

How to import a PowerShell module for administrators only?


When importing a PowerShell module that

#Requires -RunAsAdministrator

from my PowerShell profile, it throws an ScriptRequiresElevation,Microsoft.PowerShell.Commands.ImportModuleCommand error.

How can I either


Solution

  • The easiest is to add the condition check in your profile script, you can add the check to see if you are running as Administrator:

    $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
    if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
    {
        Import-Module NeedsAdminModule
    }