powershell

Install Modules as Admin


I want to install modules using my admin account. When I used Windows RUN AS A DIFFERENT USER I got the following error message "you don't have enough rights to install, please login with administrator account" Well, I bypassed this by using -Score CurrentUser. So it works if I do it manually...

I want to automate the process, so I converted my PS1 to EXE For some reason, when I enter my Admin username, it prompts for my password, but it does not do anything else... It was loading for like 5 minutes and nothing...

Could someone help me please?

Thank you

$userID = Read-Host -Prompt "Enter your Admin Account"
Write-Host $AdminID
runas /user:ent\$AdminID PowerShell


Install-Module -Name PowerShellGet -Force -AllowClobber -Scope CurrentUser
Install-Module -Name MicrosoftTeams -Scope CurrentUser
Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser


Import-Module ExchangeOnlineManagement
Import-Module MicrosoftTeams

Solution

  • Try this out, it should work as long as you supply valid credentials. This will prompt a UAC window before elevating.

    Recommended docs if you want to know more on this topic:

    Note, as long as your current user has admin permissions the credential prompt as well as the Credential = $cred on the code can be removed, -Verb RunAs will elevate the session. If you want to install the modules on All profiles, the -Scope CurrentUser should be removed.

    $commands = {
        Install-Module -Name PowerShellGet -Force -AllowClobber -Scope CurrentUser
        Install-Module -Name MicrosoftTeams -Scope CurrentUser
        Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser
    }
    
    $arguments = @{
        FilePath     = 'powershell.exe'
        Credential   = Get-Credential -Message 'Supply Admin Credentials'
        ArgumentList = @(
            '-ExecutionPolicy', 'ByPass'
            '-NoExit'
            '-NoProfile'
            '-Command'
            "
            Start-Process powershell.exe -Verb RunAs -ArgumentList @(
                '-ExecutionPolicy', 'ByPass'
                '-NoExit', '-NoProfile'
                '-EncodedCommand'
                '$([System.Convert]::ToBase64String(
                    [System.Text.Encoding]::Unicode.GetBytes($commands.ToString())))')
            ")
    }
    Start-Process @arguments