为什么大多数输出​​未重定向到文件? [英] Why is most of the output not being redirected to the file?

查看:86
本文介绍了为什么大多数输出​​未重定向到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个批处理脚本,该脚本可以打开PS会话作为绕过策略,并执行需要执行的PS脚本

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}"

我得到了我想要的东西:输出到控制台和文件.但是,当我在执行完成后打开文件时,它只包含控制台上打印的其他所有内容的一行. 99%的输出未重定向到日志文件.

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.

那是为什么?

还有一件事,我想将此蝙蝠文件用于任何PS脚本,因此我尝试执行以下操作:

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}"

当我打开CMD并键入以下内容时:

and when i open a CMD and type the following:

runPS.bat main.ps1 DB1

它抱怨:

不能将术语"main.ps1"识别为cmdlet,函数,脚本文件或 可操作的程序.检查名称的拼写,或者是否包含路径,请验证路径是否正确,然后尝试 再次.

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.

推荐答案

@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%'}"
)

for循环将获取第一个参数的完整路径 如果没有通过全路径.

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.

经过PS1测试以显示传递的参数:

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

这篇关于为什么大多数输出​​未重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆