Petr Neu
Petr Neu

Reputation: 11

Running script as admin with executionpolicy bypass starting from user

My powershell code is first run as user then when user wants to do something else I want to launch another script but that script required admin privileges so I have this command in my first powershell to run the required script as admin

Start-Process -WindowStyle Hidden -FilePath PowerShell.exe -Verb Runas -ArgumentList "-executionpolicy bypass -File $path"

But this just does nothing it doesn't even run the file

Upvotes: 1

Views: 3668

Answers (1)

ArcSet
ArcSet

Reputation: 6860

I wrote a function for about what you are trying to do

<#

.SYNOPSIS
Creates new powershell consoles

.DESCRIPTION
Used to create new powershell consoles running as same rights unless Elevated is selected in which case it runs as administrator

.EXAMPLE
New-PowershellConsole -Count 2 -Elevated -Exit

.PARAMETER Count
Starts up this many consoles

.PARAMETER Elevated
Starts Consoles as Administrator

.PARAMETER Exit
Closes the current powershell console

#>
function New-PowershellConsole {
    param(
        [int]$Count = 1,
        [switch]$Elevated,
        [switch]$Exit
    )
    if ($(new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) -or $($Elevated -eq $True)) {
        while ($Count -gt 0){
            Start-Process powershell -Verb runAs -ArgumentList "-NoExit -Command `"Set-Location $((Get-Location).path)`"";
            $Count--
        }
    } else {
        while ($Count -gt 0){         
            Start-Process powershell -ArgumentList "-NoExit -Command `"Set-Location $((Get-Location).path)`"";
            $Count--
        }
    }
    If($Exit){
        exit
    }
}

Based off your message it looks like you want to run a new powershell console as admin

Start-Process powershell -Verb runAs -ArgumentList "-NoExit";

I suggest to avoid errors is to check if the user is a administrator

if ($(new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) -or $($Elevated -eq $True)) {
    Start-Process powershell -Verb runAs -ArgumentList "-NoExit";
}

Upvotes: 1

Related Questions