我有 powershell 进程,并且我正在调用 Start-Process 或 System.Diagnostic.Process 以作为不同用户启动子进程(以获取其他用户环境变量)
我尝试使用重定向输出,但它不起作用。下面是代码
$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()
我还尝试以最小化或隐藏方式运行此进程,但它不起作用。
任何帮助将不胜感激 问候 Ajax
最佳答案
这是一个可以完成您想要的功能的函数:
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 作为机制,您将无法运行此隐藏
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 - 将子进程的输出重定向到父进程 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323922/