Powershell 2:将每一位输出定向到文件的简单方法?
我有一个脚本可以生成各种形式的输出 - 主要是标准输出和错误通道。
我尝试过类似的事情:
script.ps1 > $somefile 2>&1
script.ps1 | tee-object <args>
script.ps1 | out-file <args>
我也尝试过开始转录/停止转录。所有这些方法都有其缺点,或者只是看起来不起作用。
与 UNIX 风格调用最接近的 powershell 等效项是什么:
myScript.ps1 > $somefile 2>&1
当我在 powershell 中尝试上述命令时,我在控制台上看到所有输出,并且留下了一个名为“output”的 0 长度文件。什么给?
编辑:好的,我相信我的大部分问题在于我正在使用 Write-Host,我认为它绕过了标准输出流。但是,我非常担心,如果我将 Write-Host 语句切换为 Write-Output,那么我最终会破坏所有函数的返回值,或者以其他方式严重搞砸我的脚本。
处理 Write-Host 条目以便我能够可靠地将所有输出和错误捕获到同一文件的最谨慎选择是什么?另外,我正在使用 Write-Host 的着色功能...我猜如果我想转储到日志文件,我将不得不放弃它。
或者甚至更好,是否可以设置一个命令行参数,例如“-console”来控制是否使用 Write-Host 或其他东西?我的脚本最初每天手动和交互地运行数十次。然后,它将在未来几年中每天每小时运行一次,其中将需要所有输出/错误的日志。
I have a script that generates output of various forms - mostly standard output and error channels.
I have tried things like:
script.ps1 > $somefile 2>&1
script.ps1 | tee-object <args>
script.ps1 | out-file <args>
I've also tried start-transcript / stop-transcript. All of these methodologies have their drawbacks, or just don't plain seem to work.
What is the closest powershell equivalent of the UNIX-style invocation:
myScript.ps1 > $somefile 2>&1
When I try the above command in powershell, I see all output on console, and a 0-length file called 'output' is left behind. What gives?
EDIT: Okay, I believe most of my problem lies in the fact I'm using Write-Host, which I think bypasses the standard output stream. However, I am very worried that if I switch my Write-Host statements to Write-Output, then I'll end up corrupting the return values of all of my functions, or seriously screwing my script up some other way.
What is my most prudent option of dealing with the Write-Host entries so that I can reliably capture all output and errors to the same file? Also, I'm using colorization capabilities from Write-Host... I'm guessing I'll have to give that up if I'm looking to dump to log files.
Or even better, is it possible to set up a command-line argument, say, '-console' that controls whether Write-Host or something else is used? My script is initially being run dozens of times a day manually and interactively. It will then run once an hour every day for years to come, where logs of all output/errors will be desired.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
做而不是做
你可以
Instead of doing
You can do
我会将精力集中在开始和停止成绩单上。我在一个 3 层系统中使用它,该系统涉及一个客户端调用服务器上的脚本,该脚本通过 PSRemote 代理对另一个服务器的调用,它对我来说非常出色。输出干净且易于解析。
除非将其输出通过管道传输到 Out-Default,否则它会因本机命令而失败。而且你无法喜欢它。您一次只能得到一份成绩单,但一份就足够了。
I'd focus my efforts on start and stop transcript. I use it in a 3-tier system involving a client calling a script on a server that proxies a call to another server via PSRemote, and it does a splendid job for me. The output is clean and easily parsed.
It fails with native commands, unless you pipe its output to Out-Default. And you can't get to fancy with it. One transcript is all you get at a time, but one's enough.