【问题标题】:PowerShell Start-Process with other user credential and waitPowerShell 使用其他用户凭据启动进程并等待
【发布时间】:2016-03-09 07:03:06
【问题描述】:

我正在使用具有提升权限的其他用户使用 PowerShell 启动一个进程。

$username = "username" 
$password = "password"
$startWithElevatedRights = "notepad"

$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ‘,  $startWithElevatedRights, ‘ -Wait -verb runas}'

我知道将用户凭据写入代码是一种不好的风格,但它在全自动过程中使用,因此这是必要的。 我的问题是,我不能等到过程(最后一行代码)完成。内部进程按预期等待。

我试过参数-Wait, * |等待进程,* | Out-Null,返回值(始终为空) 没有任何效果。

是否有任何解决方案等到进程退出? 如果 PowerShell 2.0 有任何解决方案,那将是我用例的最佳选择。

【问题讨论】:

  • 您是否需要在您的脚本已经执行的 powershell 进程中启动一个新的 powershell 进程以启动记事本?
  • 你能把代码贴在你使用了 -Wait 参数的地方吗?
  • @arco444 我不需要启动另一个 PowerShell,但我需要提升权限。在这种情况下,记事本只是一个假人。
  • @DanL 我只是在 Start-Process 行中的任何地方都尝试过。在凭据之后和之前,在完整参数列表之后和参数列表内(在 ' 字符之间)...
  • 对不起,我忘了在内部启动过程中添加工作“等待”。我编辑了我的帖子以匹配所描述的问题。

标签: powershell wait start-process


【解决方案1】:

您可以使用PassThru 参数从Start-Process 获取Process 对象,然后使用wait for it to exit

$username = "username" 
$password = "password"
$startWithElevatedRights = "notepad"

$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ',  $startWithElevatedRights, ' -Wait -verb runas}'

$ps.WaitForExit()

【讨论】:

  • 我试过了,它确实适用于我的用例。感谢您的回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
相关资源
最近更新 更多