You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何捕获bittrex-api.ps1的输出至变量供主脚本使用?

Capturing Bittrex API Script's Write-Host Output into a Variable

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-Error for errors, you’ll need to redirect the error stream too with 2>&1 (e.g., .\bittrex-api.ps1 6>&1 2>&1).
  • The 6>&1 syntax 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:03:33