Search code examples
powershellpowershell-4.0

Start-Process throwing Error When trying to Self Elevate


Not sure why I am getting this error when trying to self elevate.

param(
    $adminUser
)

# Self-elevate the script to administrator if required

if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
 if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
  $CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
  Start-Process -FilePath PowerShell.exe -Verb Runas -Credential "Chrysalis\$adminUser" -ArgumentList $CommandLine
  Exit
 }
}

Error:

Start-Process : Parameter set cannot be resolved using the specified named parameters.
At M:\IT Department\Scripts\Newest Client Script (Monthly Printing)\MonthlyPrintingFoldersAndShortcuts.ps1:10 char:3
+   Start-Process -FilePath PowerShell.exe -Verb Runas -Credential "Chr ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Start-Process], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand

Solution

  • The problem is that you are not using a valid set of parameters. Here's the Get-Help Start-Process parameter sets:

    SYNTAX
        Start-Process [-FilePath] <String> [[-ArgumentList] <String[]>] [-Credential <PSCredential>] [-LoadUserProfile] [-NoNewWindow] [-PassThru] [-RedirectStandardError <String>] [-RedirectStandardInput <String>] [-RedirectStandardOutput <String>] 
        [-UseNewEnvironment] [-Wait] [-WindowStyle {Normal | Hidden | Minimized | Maximized}] [-WorkingDirectory <String>] [<CommonParameters>]
    
        Start-Process [-FilePath] <String> [[-ArgumentList] <String[]>] [-PassThru] [-Verb <String>] [-Wait] [-WindowStyle {Normal | Hidden | Minimized | Maximized}] [-WorkingDirectory <String>] [<CommonParameters>]
    

    You'll notice that the first option has the -Credential (though you need a PSCredential object, not just a user name), but it does not have the -Verb parameter. The second option does have -Verb, but doesn't have -Credential. You can run the process as another user, or you can run it as the same user but elevated, but you can't do both at once. You'll have to run it as the other user, then elevate from there.