我正在编写一个简单的命令/脚本来监控Powershell中的内存使用情况,如下所示:
PS C:\Temp_Folder> while ($true) {
>> Get-Date
>> TaskList /FI "PID eq 82660" | findstr /I "Prod"
>> Start-Sleep 1 }
这个命令/脚本在提示符上显示结果,但由于我期望很多结果,所以我想输出到文件,所以这就是我所做的(参见这个官方URL):
PS C:\Temp_Folder> while ($true) {
>> Get-Date
>> TaskList /FI "PID eq 82660" | findstr /I "Prod"
>> Start-Sleep 1 } 2>&1 >>.\Geheugen.txt
但是,这似乎不起作用:
PS C:\Temp_Folder> dir Geheugen.txt
dir : Cannot find path 'C:\Temp_Folder\Geheugen.txt' because it does not exist.
At line:1 char:1
+ dir Geheugen.txt
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Temp_Folder\Geheugen.txt:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
我已经尝试过有错误重定向和没有错误重定向(
2>&1
并使用追加和覆盖(>>
和>
)),但没有运气。我做错了什么?
经过一番调查后编辑:
显然,有一个
Out-File
命令,应该按如下方式使用:
PS C:\Temp_Folder> while ($true) {
>> Get-Date
>> TaskList /FI "PID eq 82660" | findstr /I "Prod"
>> Start-Sleep 1 } 2>&1 | Out-File -FilePath .\Geheugen.txt
这很令人困惑:
在 DOS(Windows 命令行)中,始终可以使用标准重定向运算符
>
和 >>
来重定向到文件。显然,Windows Powershell 中也预见到了这些运算符,但“有时”它们不起作用。有人对此有时有准确的描述吗?
额外测试:
如您所见,Out-File
似乎不起作用:
while ($true) {
>> Get-Date
>> TaskList /FI "PID eq 4240" | findstr /I "Prod"
>> Start-Sleep 1 } | Out-file -FilePath .\Prod_Server_Monitoring.txt
我收到以下错误消息:
At line:4 char:17
+ Start-Sleep 1 } | Out-file -FilePath .\Prod_Server_Monitoring.tx ...
+ ~
An empty pipe element is not allowed.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : EmptyPipeElement
它也不会写入文件,但这很正常:您正在尝试写入
while
本身的成功和错误流,而不是它运行的代码的内容。
您需要将整个while(){}
包含在变量(es:
$(while{}) >> 'file.txt'
)或脚本块(es:& { while(){} } >> 'file.txt'
)中但是,如果您想保留终端输出,您可能需要使用
Tee-Object
。
问题作者编辑:
我已将 while 循环放入变量中,这确实解决了问题:
$(while ($true) {
...
}) >>.\Prod_Server_Monitoring.txt
| Out-File
,因为循环不返回任何值。您需要在特定命令之后执行此操作。还添加 -Append 标志以不覆盖您的文件
while ($true) {
Get-Date
TaskList /FI "PID eq 4240" | findstr /I "Prod" | Out-File
.\Prod_Server_Monitoring.txt -Append
Start-Sleep 1
}