Search code examples
powershellrunas

Use additional arguments to start-process Powershell -verb runas


This pulled from a website online, and with added if...else it works fine.

if(!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
  $Arguments = "& '" + $myInvocation.MyCommand.Definition + "'"
  start-process Powershell -verb runAs -argumentlist $Arguments
}
else
{
  get-ExecutionPolicy
  pause
}

However I can't seem to figure out how to add -executionpolicy bypass into the call.

I tried using $Arguments = "& -executionpolicy bypass '" + $myInvocation.MyCommand.Definition + "'" but the elevated window appears, and disappears, without displaying the execution policy that it does if I exclude the bypass part of the string.

How can I supply additional arguments to such a call?


Solution

  • Whatever code you pass-in to PowerShell -Command is already invoked without the need for the call operator &, if you remove it from $Arguments then your code works.

    if (!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        $Arguments = "-ExecutionPolicy ByPass " + '"' + $myInvocation.MyCommand.Definition + '"'
        Start-Process Powershell -Verb RunAs -ArgumentList $Arguments
        return
    }
    
    Get-ExecutionPolicy
    Pause
    

    You can also make an array out of $Arguments and it would be valid too:

    $Arguments = "`"$($myInvocation.MyCommand.Definition)`"", '-ExecutionPolicy', 'ByPass'
    

    And lastly, if .MyCommand.Definition resolves to a file path, then you should consider using PowerShell -File instead:

    $Arguments = "-ExecutionPolicy ByPass -File `"$($myInvocation.MyCommand.Definition)`""