Cataster
Cataster

Reputation: 3521

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

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.

Upvotes: 0

Views: 191

Answers (1)

michael_heath
michael_heath

Reputation: 5372

@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

Upvotes: 1

Related Questions