Why is most of the output not being redirected to the file?

自作多情 提交于 2020-01-06 04:31:28

问题


I have a batch script that opens a PS session as bypass policy and executes whatever the PS script needs to execute

set "psFile=.\main.ps1"

Powershell.exe -ExecutionPolicy ByPass -Command "&{%psFile% %2 %3 %4 %5 %6 | Tee-Object -FilePath log.txt}"

I am getting what I want: output to both console AND file. however, when I opened the file after the execution was finished, it only contained like one line from everything else that was printed on the console. 99% of the output was not redirected to the log file.

Why is that?

Also, one more thing, I would like to use this bat file for any PS script, so I tried doing something like this:

set psFile="%1"

Powershell.exe -ExecutionPolicy ByPass -Command "&{%psFile% %2 %3 %4 %5 %6 | Tee-Object -FilePath log.txt}"

and when i open a CMD and type the following:

runPS.bat main.ps1 DB1

it complains:

The term 'main.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.


回答1:


@echo off
setlocal

rem Get fullpath of 1st argument.
for %%A in ("%~1") do set "psfile=%%~fA"

rem Save log in same directory of 1st argument.
set "logfile=%~dp1log.txt"

if defined psfile (
    rem Run the PS1 file with remaining arguments and tee the piped stdout stream.
    Powershell.exe -ExecutionPolicy ByPass -Command "&{&'%psFile%' '%~2' '%~3' '%~4' '%~5' '%~6' | Tee-Object -FilePath '%logfile%'}"
)

The for loop will get the full path of the 1st argument if a fullpath was not passed.

The log file is recommended as a fullpath, to insure success, and the knowing where it is saved.

The single quotes surrrounding the paths helps with any possible whitespace etc.

Tested with PS1 to show passed arguments:

$args

which seems to show all stdout OK with a test.

To include other streams, view About Redirection



来源:https://stackoverflow.com/questions/56333784/why-is-most-of-the-output-not-being-redirected-to-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!