powershell - 以管理员身份运行 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)”之类的文件夹。
解决方案
$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
}
推荐阅读
- javascript - 用于选择如何导出 CSV 的函数及其选择器
- hibernate - 如果数据库表有 10 列,我们可以编写 5 列的 pojos
- jquery-animate - Jquery animate 函数不起作用:左侧属性的关键帧值无效
- c++ - Qt QSerialport 拔出设备未关闭
- r - 忽略未知的美学:填充
- python - TypeError: 'numpy.ndarray' 对象在为逻辑回归执行 RandomizedSearchCV 时不可调用
- javascript - 如果未检测到更改,如何使用 jquery/javascript 检测更改并防止在 GSP/HTML 中提交表单
- ios - 全球 iPhone 上的匹配时间 - 同步播放视频?
- oracle - 如何在 oracle 触发器中获取准确的更新列名?
- wordpress - 上传 wordpress 文件大小超过 10mb 的 Http 错误