PowerShell中如何捕获bittrex-api.ps1的输出至变量供主脚本使用?
Hey there! I’ve dealt with this exact scenario before—capturing Write-Host output from a called script can be tricky because it doesn’t flow through the standard success stream by default. Let’s break down how to do this properly based on your PowerShell version:
For PowerShell 5.1 or Newer
Starting in PowerShell 5.0, Write-Host writes to the Information Stream (stream number 6) instead of directly to the console. To capture this, you can redirect the information stream to the success stream using 6>&1 when calling the script:
# Capture all output (including Write-Host messages) into a variable $bittrexResults = .\bittrex-api.ps1 6>&1
Now you can filter the variable to extract the specific error message you’re looking for:
# Find lines containing the Bittrex error marker $capturedError = $bittrexResults | Where-Object { $_ -match 'BITTREX ERROR:' } # Use the error in your main script if ($capturedError) { Write-Error "API call failed: $($capturedError -replace 'BITTREX ERROR: ', '')" # Add your error handling logic here (e.g., log to file, retry, etc.) }
For PowerShell 4.0 or Older
In older PowerShell versions, Write-Host writes directly to the console host, so stream redirection won’t work. Instead, you can temporarily redirect the console output to a string writer:
# Save the original console output stream $originalConsoleOut = [Console]::Out # Create a string writer to capture output $stringWriter = New-Object System.IO.StringWriter [Console]::SetOut($stringWriter) # Execute the Bittrex API script .\bittrex-api.ps1 # Restore the original console output [Console]::SetOut($originalConsoleOut) # Get the captured output as a string $bittrexResults = $stringWriter.ToString() # Filter for the error message (split into lines if needed) $capturedError = $bittrexResults -split "`n" | Where-Object { $_ -match 'BITTREX ERROR:' }
Key Notes
- If the Bittrex script also uses
Write-Errorfor errors, you’ll need to redirect the error stream too with2>&1(e.g.,.\bittrex-api.ps1 6>&1 2>&1). - The
6>&1syntax merges the information stream into the success stream, so your variable will contain all output from the script—use filtering to isolate what you need.
内容的提问来源于stack exchange,提问作者Mister Iks

