Search code examples
powershelladministrator

Running PowerShell script as Administrator all arguments are empty


I've an issue when I try to to run my PowerShell script (named autoupdateWindows.ps1) as an admin below. I want to move/rename some folders content like "Program Files (x86)" but I need to have an administrator PowerShell as I said.

Param(
    [string]$installDir,
    [string]$appDir,
    [string]$installDirName,
    [string]$appDirName
)

#Elevate Powershell as admin it isn't
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
    $arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    break
}

Write-Output $installDir
Write-Output $appDir
Write-Output $installDirName
Write-Output $appDirName

Remove-Item -path $installDir\$installDirName -recurse
Move-Item -path $appDir -destination $installDir
Rename-Item -path $installDir\$appDirName -newname $installDirName

#Pause
if ($Host.Name -eq "ConsoleHost") {
    Write-Host "Press any key to continue..."
    $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}

And here is the the command line I use in my PowerShell window

powershell.exe -file .\autoupdateWindows.ps1 "c:\Program Files (x86)", "c:\users\dcommun\downloads", "installDir", "appDir"

So when I use it, all of the four parameters (arguments) are empty. But when I remove the first if block to start PowerShell as an admin the parameters are correctly filled. I can do it only in this way (in the script) to have acess to folders like "Program Files (x86)".


Solution

  • $MyInvocation.MyCommand.Definition is just the script without arguments, so you're effectively omitting the arguments when elevating the script. Define $arguments as an array of the script and the other parameters.

    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]'Administrator')) {   
        $arguments = '-File', $MyInvocation.MyCommand.Definition,
                     $installDir, $appDir, $installDirName, $appDirName
        Start-Process 'powershell.exe' -Verb RunAs -ArgumentList $arguments -NoNewWindow -Wait
        exit $LastExitCode
    }