我是在 Powershell 中编写脚本的新手,我遇到了一个问题,每当我以管理员身份运行脚本时,它都会自动失败。运行脚本通常会成功,但作为管理员,它会打开一瞬间并立即再次关闭(* 根据@iRon 的建议,情况不再如此)。老实说,我不确定这是编程问题还是 Windows 问题,所以我把它放在这里 - 如果这更适合超级用户堆栈,请告诉我。
最终目标是能够从批处理脚本中调用脚本,以便我可以在 Windows 更新因防火墙设置错误而搞砸的 PC 上远程重新构建受信任的根证书。但我不能这样做,除非我让它以管理员身份运行。
我当前的代码如下(来自this tutorial)(除了扩展名之外,它们的名称都相同,因此是 %~dpn0):
批次:
@ECHO OFF
PowerShell.exe -NoExit -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -noexit -wait -File ""%~dpn0.ps1""' -Verb RunAs}"
pause
POWERSHELL:
echo "Hello World!"
if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{Write-Output 'Running as Administrator!'}
else
{Write-Output 'Running Limited!'}
Pause
附加信息:我在 Windows 10 21H2 上使用 powershell 版本 10.0.19041.1023 运行它。我可以在提升的 powershell 窗口中单独运行这些命令。
在@iRon 的帮助下,我得到了实际的错误消息,尽管脚本仍然无法运行:
x86 : The term 'x86' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:31
+ -wait -File [path]\Program Files (x86)\Lansweeper\PackageShare\Scripts\ ...
+ ~~~
+ CategoryInfo : ObjectNotFound: (x86:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
答案 0 :(得分:0)
问题是您从 cmd.exe 实例运行它,这意味着您需要使用反斜杠转义嵌套的双引号:
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "& {Start-Process $Env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe -ArgumentList '-ExecutionPolicy RemoteSigned -NoExit -File \"%~dpn0.ps1\"' -Verb RunAs}"
或者没有不必要的&{…}
:
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Start-Process $Env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe -ArgumentList '-ExecutionPolicy RemoteSigned -NoExit -File \"%~dpn0.ps1\"' -Verb RunAs"