2012-07-04 88 views
1

我有powershell進程,我打開啓動進程或System.Diagnostic.Process以不同的用戶身份啓動子進程(獲取其他用戶環境變量)將子進程的輸出重定向到父進程 - Powershell

我嘗試使用redirectoutput但它不起作用。下面是代碼

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

另外我試圖運行此過程爲最小化或隱藏,但它不起作用。

任何幫助將是非常讚賞 問候 阿賈克斯

回答

3

下面是會做一個功能你想要什麼:

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屬性爲 set,調用非託管的CreateProcessWithLogonW函數,即使CreateNoWindow屬性 的值爲true或WindowStyle屬性值爲Hidden, 也會在新窗口中啓動該過程。 - source

+0

我從來沒有見過這麼明確的解釋。我非常感謝你,我會立即嘗試一下。再次非常感謝:-) – ajax

+0

嗨,你知道如何成功傳遞參數數組我想通過這個「[Microsoft.Win32.Registry] :: SetValue('HKEY_CURRENT_USER \ Environment','$ keyVar',' $ valueVar','$ regType')「3次在參數數組中。但我得到一個異常 – ajax

+0

雅得到它解決。謝謝 – ajax

相關問題