如何使用快捷方式以管理员身份运行 PowerShell 脚本?

问题描述

我正在尝试使用快捷方式以管理员身份运行 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'

有人可以帮忙吗?

解决方法

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\"}"