簡體   English   中英

從腳本中的 Windows 批處理文件重定向 output

[英]Redirect output from a Windows batch file within the script

我正在嘗試制作一個 Windows 批處理文件(主腳本),將所有 output 重定向到一個文件,同時仍在屏幕上顯示它。 我無法更改調用主腳本的所有代碼 - 我需要更改主腳本本身。

我有一個解決方案需要通過從另一個 bat 文件 (tee_start.bat) 再次調用來“引導”主腳本。 我確定我想避免的是重構調用 main.bat 的所有其他腳本以使用 tee 命令——如果我可以在 main.bat 中放入一些新代碼,這將是一個更小、更安全的更改。

有沒有一種方法可以做到這一點而不涉及像我在下面所做的那樣重新啟動主文件? 例如,是否有一個 cmd.exe 或 powershell.exe 命令說“獲取我當前的 STDOUT 並發球”——或者發球是否以某種方式支持這種行為而我錯過了它? 或者,我是否應該接受我已經實施的侵入性最小的方法?

我已經實施了如下解決方案:

主程序

REM this is an example of bootstrap mode - it will restart this main script with all output logged
call tee_start.bat %~dpnx0 %*

echo This output should appear both in the screen console and in a log file

tee_start.bat

REM in order to bootstrap the output redirection - this script gets called twice - once to initialize logging with powershell tee command
REM second time, it just echoes log information and returns without doing anything
if x%LOG_FILE% neq x (
    echo Bootstrapped Process: %1%
    echo Escaped Arguments: %ADDL_ARGS%
    echo Log File: %LOG_FILE%
    goto :EOF
)

set ADDL_ARGS=
:loop_start
shift
if x%1 == x goto :after_loop
REM preserve argument structure (quoted or not) from the input
set ADDL_ARGS=%ADDL_ARGS% \"%~1\"
goto loop_start
:after_loop

SET LOG_FILE=/path/to/some/logfile.log

powershell "%1% %ADDL_ARGS% 2>&1 | tee -Append %LOG_FILE%"

我建議采用以下方法,這種方法沒有輔助功能。 tee_start.bat文件:

main.bat內容(輸出到當前文件夾下的log.txt ,根據需要調整):

@echo off & setlocal

if defined LOGFILE goto :DO_IT

    set "LOGFILE=log.txt"
    :: Reinvoke with teeing
    "%~f0" %* 2>&1 | powershell -NoProfile -Command "$input | Tee-Object -FilePath \"%LOGFILE%\"; \"[output captured in: %LOGFILE%]\""
    exit /b


:DO_IT

:: Sample output
echo [args: %*]
echo to stdout
echo to stderr >&2
echo [done]
  • Tee-Object使用固定的字符編碼,特別是 Windows PowerShell ( powershell.exe ) 中的“Unicode” (UTF-16LE),以及 PowerShell (Core) 7+ ( pwsh.exe ) 中的 (BOM-less UTF-8) .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM