Aar*_* Li 5 powershell working-directory elevated-privileges
我正在尝试使用快捷方式以管理员身份运行 PowerShell 脚本。我尝试了很多方法,但还是不行:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit -Verb RunAs Start-Process powershell.exe -ArgumentList '-file C:\project\test.ps1'
Run Code Online (Sandbox Code Playgroud)
使用此命令,它将创建两个 PowerShell 窗口,并关闭一个窗口。
我也尝试过这个:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit Start-Process powershell.exe -Verb RunAs -File 'C:\project\test.ps1'
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
这就能解决问题:
powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"
Run Code Online (Sandbox Code Playgroud)
首先,您必须调用 PowerShell 才能执行Start-Process. 此时您不需要任何其他参数,因为您只需使用第一个 PowerShell 来启动另一个 PowerShell。你这样做:
powershell.exe -Command "& {...}"
Run Code Online (Sandbox Code Playgroud)
您可以在大括号内插入任何脚本块。首先,您将检索当前工作目录 (CWD) 以在新启动的 PowerShell 中进行设置。然后调用 PowerShell 并Start-Process添加-Verb RunAs参数来提升它:
$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList ...
Run Code Online (Sandbox Code Playgroud)
然后您需要将所有所需的 PowerShell 参数添加到ArgumentList. 就您而言,这些将是:
-ExecutionPolicy ByPass -NoExit -Command ...
Run Code Online (Sandbox Code Playgroud)
最后,将要执行的命令传递给参数-Command。基本上,您想调用脚本文件。但在此之前,您将 CWD 设置为之前检索到的目录,然后调用您的脚本:
Set-Location $wd; C:\project\test.ps1
Run Code Online (Sandbox Code Playgroud)
总共:
powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12956 次 |
| 最近记录: |