PowerShell 使用其他用户凭据启动进程并等待 [英] PowerShell Start-Process with other user credential and wait

查看:27
本文介绍了PowerShell 使用其他用户凭据启动进程并等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am starting a process with PowerShell using another user with elevated rights.

$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}'

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

I know it's bad style to write user credentials to code, but it is used within full automated procedures, so this is necessary. My problem is, that I cannot wait until the process (last code line) finished. The inner process waits as expected.

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

I tried the parameter -Wait, * | Wait-Process, * | Out-Null, with return Value (which is always null) Nothing works.

有什么解决方案可以等到进程退出吗?如果 PowerShell 2.0 有任何解决方案,那将是我的用例的最佳选择.

Is there any solution waiting until the process has exited? If there is any solution for PowerShell 2.0 it would be the best for my use case.

推荐答案

您可以获得 Process 对象从 Start-Process 使用 PassThru 参数然后 等待它退出.

You can get Process object from Start-Process using PassThru parameter and then 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()

这篇关于PowerShell 使用其他用户凭据启动进程并等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆