Powershell将可执行文件输出到文本文件

Powershell将可执行文件输出到文本文件,powershell,Powershell,我正在尝试为工作编写Powershell脚本,该脚本将w32tm.exe\monitor的输出输出并将所有内容输出到文本文件中。我正在尝试以下代码,但由于我能够创建文本文件,因此出现了一些错误,但没有写入任何内容: #Take output of w32tm.exe and output into a plain text file $file = "C:\Documents and Settings\a411882\My Documents\Scripts\timeScript.txt" $e

我正在尝试为工作编写Powershell脚本,该脚本将w32tm.exe\monitor的输出输出并将所有内容输出到文本文件中。我正在尝试以下代码,但由于我能够创建文本文件,因此出现了一些错误,但没有写入任何内容:

#Take output of w32tm.exe and output into a plain text file
$file = "C:\Documents and Settings\a411882\My Documents\Scripts\timeScript.txt"
$executable = "w32tm.exe /monitor"
invoke-expression $executable | out-file -filepath $file
我做错了什么?我是Powershell的新手,因此任何建议都将不胜感激

编辑: 我可以在运行此操作时在控制台上显示所有数据,但是我希望数据写入文本文件

编辑2:
我设法把所有东西都输出了。我希望尽量避免使用>运算符将内容写入文本文件,以期进一步了解out-file cmdlet,但使用简单的调用表达式$executable>$file可以完成任务。我仍然不明白为什么cmdlet不能正常工作

也许
调用表达式
没有正确地将输出发送到stdout?我没想到会这样,但奇怪的事情发生了。尝试单独运行
w32tm.exe

$file = "C:\Documents and Settings\a411882\My Documents\Scripts\timeScript.txt"
w32tm.exe /monitor | Out-File -FilePath $file

也许
Invoke Expression
没有正确地将输出发送到stdout?我没想到会这样,但奇怪的事情发生了。尝试单独运行
w32tm.exe

$file = "C:\Documents and Settings\a411882\My Documents\Scripts\timeScript.txt"
w32tm.exe /monitor | Out-File -FilePath $file

您可以使用
Start Process
,它还允许您重定向错误输出:

Start-Process w32tm.exe -ArgumentList "/monitor" -Wait -RedirectStandardOutput "output.txt" -RedirectStandardError "error.txt"

您可以使用
Start Process
,它还允许您重定向错误输出:

Start-Process w32tm.exe -ArgumentList "/monitor" -Wait -RedirectStandardOutput "output.txt" -RedirectStandardError "error.txt"

只需使用
invoke expression$executable
就可以为控制台提供预期的输出吗?在我的会话中使用您的代码,只需更改我的配置文件目录的路径即可!只需使用
invoke expression$executable
就可以为控制台提供预期的输出吗?在我的会话中使用您的代码,只需更改我的配置文件目录的路径即可!