我正在批处理文件中运行PowerShell脚本。该脚本获取一个网页,并检查页面的内容是否是字符串“OK”。
PowerShell脚本向批处理脚本返回错误级别。
批处理脚本由一个FTP自动化程序ScriptFTP执行。如果发生错误,我可以让ScriptFTP通过电子邮件将完整的控制台输出发送给管理员。
在PowerShell脚本中,我希望输出来自网站的返回值,如果它不是“OK”,那么错误消息将包含在控制台输出中,从而包含在状态邮件中。
我是PowerShell的新手,不确定要使用哪个输出函数。我可以看到三个:
Write-Host
写输出
写错误
用什么东西来写入Windows的标准输出是正确的?
您根本无法让PowerShell提交这些讨厌的换行符。没有脚本或cmdlet可以做到这一点。
当然Write-Host完全是胡说八道,因为你不能从它重定向/管道!你只需要自己写:
using System;
namespace WriteToStdout
{
class Program
{
static void Main(string[] args)
{
if (args != null)
{
Console.Write(string.Join(" ", args));
}
}
}
}
E.g.
PS C:\> writetostdout finally I can write to stdout like echo -n
finally I can write to stdout like echo -nPS C:\>
您根本无法让PowerShell提交这些讨厌的换行符。没有脚本或cmdlet可以做到这一点。
当然Write-Host完全是胡说八道,因为你不能从它重定向/管道!你只需要自己写:
using System;
namespace WriteToStdout
{
class Program
{
static void Main(string[] args)
{
if (args != null)
{
Console.Write(string.Join(" ", args));
}
}
}
}
E.g.
PS C:\> writetostdout finally I can write to stdout like echo -n
finally I can write to stdout like echo -nPS C:\>
我认为在这种情况下,您将需要Write-Output。
如果你有一个脚本
Write-Output "test1";
Write-Host "test2";
"test3";
然后,如果你调用带有重定向输出的脚本,就像你的脚本。Ps1 > out.txt,你将得到屏幕上的test2 test1\ntest3\n在“out.txt”。
请注意,"test3"和Write-Output行总是会在你的文本中追加一个新行,在PowerShell中没有办法停止这一点(也就是说,echo -n在PowerShell的本机命令中是不可能的)。如果你想要echo -n的功能(在Bash中有点基本和简单),请参阅samthebest的答案。
If a batch file runs a PowerShell command, it will most likely capture the Write-Output command. I have had "long discussions" with system administrators about what should be written to the console and what should not. We have now agreed that the only information if the script executed successfully or died has to be Write-Host'ed, and everything that is the script's author might need to know about the execution (what items were updated, what fields were set, et cetera) goes to Write-Output. This way, when you submit a script to the system administrator, he can easily runthescript.ps1 >someredirectedoutput.txt and see on the screen, if everything is OK. Then send the "someredirectedoutput.txt" back to the developers.