2

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

ajax
  • 317
  • 8
  • 17

1 Answers1

4

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()
}

According to MSDN you won't be able to run this hidden if you use Process.Start as the mechanism

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

xcud
  • 14,422
  • 3
  • 33
  • 29
  • I have never seen such a crystal clear explanation. I am really thankful to you I will immediately try this out. Once again really appreciated :-) – ajax Jul 05 '12 at 06:45
  • Hi, Do you know how to successfully pass an arguments array I am trying to pass this "[Microsoft.Win32.Registry]::SetValue('HKEY_CURRENT_USER\Environment','$keyVar','$valueVar','$regType')" for 3 times in the arguments array.but i get a Exception – ajax Jul 05 '12 at 07:23