在一個相當受限制的環境中,我基本上只允許使用Powershell + Plink,如果我想自動化一些任務。Powershell - 輸入stdin之後輸入stdout/stderr不再有效
我想創建一個函數:
- 顯示輸出如果需要
- 捕獲所有的輸出(stdout和stderr),使其後可用於進一步分析或記錄來安慰到達/文件/無論
- 輸入密碼自動
不幸的是,我輸入密碼輸出捕獲停止線後。當我僅捕獲stdout時,它曾經工作。在捕捉到stderr之後,沒有更多的運氣。
代碼:
function BaseRun {
param ($command, $arguments, $output = "Console")
$procInfo = New-Object System.Diagnostics.ProcessStartInfo
$procInfo.RedirectStandardOutput = $true
$procInfo.RedirectStandardError = $true
$procInfo.RedirectStandardInput = $true
$procInfo.FileName = $command
$procInfo.Arguments = $arguments
$procInfo.UseShellExecute = $false
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $procInfo
[void]$process.Start()
$outputStream = $process.StandardOutput
$errorStream = $process.StandardError
$inputStream = $process.StandardInput
$outputBuffer = New-Object System.Text.StringBuilder
Start-Sleep -m 2000
$inputStream.Write("${env:password}`n")
while (-not $process.HasExited) {
do {
$outputLine = $outputStream.ReadLine()
$errorLine = $errorStream.ReadLine()
[void]$outputBuffer.Append("$outputLine`n")
if (($output -eq "All") -or ($output -eq "Console")) {
Write-Host "$outputLine"
Write-Host "$errorLine"
}
} while (($outputLine -ne $null) -and ($errorLine -ne $null))
}
return $outputBuffer.ToString()
}
我沒有現成的解決方案,但是IIRC問題是由於您正在同步進行的。所以我認爲你需要把'$ inputStream.Write'移動到一個新的線程/ RunSpace /不管。或者通過'Register-ObjectEvent $ Process OutputDataReceived ......'輸出集合'' – wOxxOm
該死的,我希望我可以避免整個異步shebang。 – oblio