2

我有 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()        

我也试图以最小化或隐藏的方式运行这个过程,但它不起作用。

任何帮助将不胜感激问候阿贾克斯

4

1 回答 1

4

这是一个可以满足您要求的功能:

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 作为机制,您将无法运行此隐藏

如果设置了 StartInfo 实例的 UserName 和 Password 属性,则调用非托管 CreateProcessWithLogonW 函数,即使 CreateNoWindow 属性值为 true 或 WindowStyle 属性值为 Hidden,它也会在新窗口中启动进程。-来源

于 2012-07-05T04:12:24.963 回答