jenkins 通过命令提示符调用具有提升权限的PowerShell脚本

sigwle7e  于 2023-03-07  发布在  Jenkins
关注(0)|答案(1)|浏览(190)

问题:

我想在非管理员命令提示符中使用提升的权限调用PowerShell脚本。当我使用“以管理员身份运行”手动打开命令提示符并输入以下行时:
powershell -ExecutionPolicy Unrestricted -Command "Start-Process Powershell -Verb RunAs -Wait -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File example.ps1 param1'"
我的脚本PowerShell脚本运行得很好。
但是,当我在非管理员命令提示符下运行它时,我看到一个PowerShell窗口出现了一瞬间,然后退出。
有没有解决这个问题的办法?

尝试

  • 同样的事情发生了,窗口打开了一瞬间,然后退出

Run Powershell script via batch file with elevated privileges

runas.exe /netonly /noprofile /user:domainadm@domain "powershell.exe -
noprofile -File "C:\Users\...\Desktop\Powershell_scripts\New-
ADuser\.ps1" -verb RunAs"
  • 同样的事情也发生在这里,窗口打开了一瞬间,然后退出

Run a Powershell script from Batch file with elevated privileges?

powershell -Command "&{ Start-Process powershell -ArgumentList '-File example.ps1 param1' -Verb RunAs}"
  • 同样的问题,窗口打开一瞬间,然后退出

Run a powershell script from cmd with elevated privileges and passing parameters

PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "example.ps1 param1"'"

上下文:PowerShell脚本用于下载在param1中指定的NSIS安装程序
编辑:脚本代码:

$param1 = $args[0]
Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms

$installer = Start-Process -FilePath $param1 -PassThru
$installerWindowName = "Installer Setup"

while (-not ($installer.MainWindowTitle -match "$installerWindowName")) {
    Start-Sleep -Milliseconds 100
    $installer.Refresh()
}
vybvopom

vybvopom1#

  • 在Windows上,从非提升的控制台启动的 * 提升的 * 进程 * 总是 * 在 * 新窗口 * 中运行,当提升的进程退出时,该窗口 * 自动关闭 *。
  • 对于 * 故障排除 *,您可以将-NoExit放在-Command参数之前,这会使提升的PowerShell会话保持打开状态,直到您手动退出它,从而允许您检查可能发生的任何错误。
  • Windows PowerShell(其CLIpowershell.exe)中,提升的进程启动时将$env:Windir\System32作为其工作目录(幸运的是,PowerShell (Core) 7+现在 * 保留 * 调用者的工作目录)。
  • 因此,使用example.ps1这样的 * 相对 * 路径 * 不起作用,您应该传递 * 完整路径 *。
  • 如果您的脚本依赖于工作目录与调用方的目录相同,则需要做更多的工作。
# Note the `"$PWD\example.ps1`" part
powershell -ExecutionPolicy Bypass -Command "Start-Process Powershell -Verb RunAs -Wait -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File `"$PWD\example.ps1`" param1'"

相关问题