简而言之
这就可以解决问题:
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。您可以按照以下方式执行:
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
参数。基本上,您要调用脚本文件。但在此之前,您将把当前工作目录设置为先前检索到的目录,然后再调用脚本:
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\"}"
powershell.exe -WindowStyle Hidden -command "& {start-process powershell -verb runas}"
- Daniel