powershell - 将子进程的输出重定向到父进程 - Powershell

标签 powershell

我有 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/

相关文章:

excel - 使用 PowerShell 更改 Excel 图表的轴类型

powershell - 在 Powershell 中启用 IIS 应用程序的身份验证

powershell - 如何在 Powershell 管道中引用前一个 "pipe"的输出?

powershell - 从 ServiceNow 检索用户名

具有启动任务的 Windows Azure 虚拟机

c# - PowerShell 脚本在 IIS 执行时不返回任何内容

powershell - Powershell(Get-Content -Path “Config.txt” -TotalCount($ aVariable + 2)[-1])获得2行而不是一行

xml - 使用Powershell编辑XML文件

Powershell 查询 - 找不到路径的一部分

powershell - 在PowerShell中将变量传递到语句 block 括号中