【问题标题】:How do I run a PowerShell script as administrator using a shortcut?如何使用快捷方式以管理员身份运行 PowerShell 脚本?
【发布时间】:2021-05-27 10:49:21
【问题描述】:

我正在尝试使用快捷方式以管理员身份运行 PowerShell 脚本。试了很多方法,还是不行:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit -Verb RunAs Start-Process powershell.exe -ArgumentList '-file C:\project\test.ps1'

使用此命令,它将创建两个 PowerShell 窗口并关闭一个窗口。

我也试过这个:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit Start-Process powershell.exe -Verb RunAs -File 'C:\project\test.ps1'

有人可以帮忙吗?

【问题讨论】:

  • 我也试过这个 "powershell.exe -ExecutionPolicy Bypass -NoExit -File "C:\project\test.ps1" " 我可以正常运行但不能以管理员身份运行,因为当我运行管理员,它将转到我的 Powershell 的路径而不是项目的路径。
  • 如果你只是想以管理员身份启动 powershell,它会是这样的powershell.exe -WindowStyle Hidden -command "& {start-process powershell -verb runas}"
  • @AaronLi 你能提供任何反馈吗?我的解决方案不适合您吗,您找到其他解决方案了吗,您的问题还存在吗?

标签: powershell working-directory elevated-privileges


【解决方案1】:

Tl;博士

这样就可以了:

powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"

说明

首先,您必须调用 PowerShell 才能执行Start-Process。此时您不需要任何其他参数,因为您只需使用第一个 PowerShell 来启动另一个。你这样做:

powershell.exe -Command "& {...}"

在花括号内,您可以插入任何脚本块。首先,您将检索当前工作目录 (CWD) 以在新启动的 PowerShell 中进行设置。然后使用Start-Process 调用PowerShell 并添加-Verb RunAs 参数以提升它:

$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList ...

然后您需要将所有所需的 PowerShell 参数添加到 ArgumentList。在您的情况下,这些将是:

-ExecutionPolicy ByPass -NoExit -Command ...

最后,您将要执行的命令传递给-Command 参数。基本上,你想调用你的脚本文件。但在此之前,您需要将 CWD 设置为之前检索到的目录,然后调用您的脚本:

Set-Location $wd; C:\project\test.ps1

总共:

powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-13
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 2012-06-25
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多