首页 > 解决方案 > 以管理员身份运行 PowerShell 脚本所有参数为空

问题描述

当我尝试以autoupdateWindows.ps1管理员身份运行我的 PowerShell 脚本(名为 )时,我遇到了问题。我想移动/重命名一些文件夹内容,例如“Program Files (x86)”,但正如我所说,我需要一个管理员 PowerShell。

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
}

这是我在 PowerShell 窗口中使用的命令行

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

所以我在使用的时候,四个参数(参数)都是空的。但是,当我删除第一个if块以以管理员身份启动 PowerShell 时,参数已正确填充。我只能以这种方式(在脚本中)访问“程序文件(x86)”之类的文件夹。

标签: powershelladministrator

解决方案


$MyInvocation.MyCommand.Definition只是没有参数的脚本,因此您在提升脚本时有效地省略了参数。定义$arguments为脚本和其他参数的数组。

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
}

推荐阅读