将子进程的输出重定向到父进程 - Powershell [英] Redirecting Output on Child Process to Parent Process - Powershell
问题描述
我有 powershell 进程,我正在调用 Start-Process 或 System.Diagnostic.Process 以作为不同的用户启动子进程(以获取其他用户的环境变量)
i have powershell process and I am calling Start-Process or System.Diagnostic.Process to start a child process as a different user (to get the other-user environment variables)
我尝试使用重定向输出,但它不起作用.下面是代码
I tried with redirectoutput but it does not work. Below is the code
$process = New-Object System.Diagnostics.Process
$startinfo = New-Object "System.Diagnostics.ProcessStartInfo"
$startinfo.FileName = "powershell"
$startinfo.UserName = $user
$startinfo.Password = $pass
$startinfo.Arguments = $arguments
$startinfo.UseShellExecute = $False
$startinfo.RedirectStandardInput = $True
$process.StartInfo = $startinfo
$process.Start() | Out-Null
$process.WaitForExist()
$output = $process.StandardOutput.ReadToEnd()
此外,我试图以最小化或隐藏的方式运行此进程,但它不起作用.
Also I am trying to run this process as Minimized or Hidden but it does not work.
任何帮助将不胜感激问候阿贾克斯
Any help will be really appreciated Regards Ajax
推荐答案
这里有一个功能可以满足您的需求:
Here's a function that'll do what you want:
function Invoke-PSCommandAsUser
{
param(
[System.Management.Automation.PSCredential]$cred,
[System.String]$command
);
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.RedirectStandardError = $True
$psi.RedirectStandardOutput = $True
$psi.UseShellExecute = $False
$psi.UserName = $cred.UserName
$psi.Password = $cred.Password
$psi.FileName = (Get-Command Powershell).Definition
$psi.Arguments = "-Command $command"
$p = [Diagnostics.Process]::Start($psi)
$p.WaitForExit()
Write-Output $p.StandardOutput.ReadToEnd()
}
根据 MSDN,如果您使用 Process.Start 作为机制,您将无法运行此隐藏
According to MSDN you won't be able to run this hidden if you use Process.Start as the mechanism
如果 StartInfo 实例的 UserName 和 Password 属性是设置,调用非托管的 CreateProcessWithLogonW 函数,它即使 CreateNoWindow 属性在新窗口中启动进程值为 true 或 WindowStyle 属性值为 Hidden.- 来源
If the UserName and Password properties of the StartInfo instance are set, the unmanaged CreateProcessWithLogonW function is called, which starts the process in a new window even if the CreateNoWindow property value is true or the WindowStyle property value is Hidden. - source
这篇关于将子进程的输出重定向到父进程 - Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!