在一个相当受限制的环境中,我基本上只允许使用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