如何让PowerShell脚本以管理员权限调用PS6/PS7版本运行
可用的修正代码如下
# 管理员权限校验 if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { $scriptPath = $MyInvocation.MyCommand.Definition # 用-File参数指定脚本路径,规避空格、特殊字符报错 $arguments = "-File `"$scriptPath`"" # 启动PowerShell 6/7并申请管理员权限 Start-Process -FilePath "pwsh" -Verb RunAs -ArgumentList $arguments Exit } # 下方放你的业务代码,比如移除/安装服务 Remove-Service -Name "MyService" # New-Service 等PS6+专属命令可以正常执行
关键说明
- 首先确保你本地已安装PowerShell 6/7,且
pwsh已加入系统环境变量PATH。如果未加入PATH,可将-FilePath "pwsh"替换为PS7的完整安装路径,比如:-FilePath "C:\Program Files\PowerShell\7\pwsh.exe" - 弃用原代码中
& '路径'的参数写法,改用pwsh原生的-File参数指定脚本路径,兼容性更强,不会因为脚本路径带空格、特殊字符报错 - 将原代码的
Break替换为Exit,避免当前非管理员权限的进程残留 - 若仍然提示
-Verb runAs参数报错,可检查PowerShell 7的安装完整性,或者尝试重启系统刷新环境变量
内容的提问来源于stack exchange,提问作者JudahA
相关产品推荐
相关产品推荐

