powershell - 是否有等待 "break"从 powershell 中的 Get-Content 等待循环?

标签 powershell

是否有等待从 Powershell 中的 Get-Content “打破”等待循环?

Get-Content "$PSScriptRoot\out.txt" -Wait

out.txt 写入的行数是固定的,我想在到达末尾时停止循环。 到目前为止,我需要用“ctrl+c”发送一个信号来完成。 在类似于

的伪代码中
Get-Content "$PSScriptRoot\out.txt" -WaitUntil 9
Get-Content "$PSScriptRoot\out.txt" -WaitUntilMatch "^LastOutput"

所以当 9 行输出时,我们打破循环。或者当达到某个正则表达式匹配时,我们可以打破循环吗?

最佳答案

您可以将值从 Get-Content 传递到 ForEach-Object,并在满足条件时中断。

例如,如果你想在达到某个正则表达式匹配时中断,你可以使用如下:

Get-Content -Path "$PSScriptRoot\out.txt" -Wait | ForEach-Object {$_ ; if($_ -Match "some regex"){break} }

如果您想在 n 行后换行,那么正如 Bruce 回答的那样,您可以使用 Select-Object -Frist n

请注意,如果文件已经包含满足条件的内容,而您只需要添加到文件中的新数据,您还应该使用 -tail 选项。

例如,如果文件已经包含 9 行,而您只想在运行命令之后将前 9 行添加到文件中,则使用:

Get-Content -Path "$PSScriptRoot\out.txt" -Wait -tail 1 | select -skip 1 -first 9

使用-tail 1,该命令将只输出文件的最后一行以及之后将添加到文件中的新数据。 -skip 1用于过滤掉最后一行,只输出新的数据。

关于powershell - 是否有等待 "break"从 powershell 中的 Get-Content 等待循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50774687/

相关文章:

PowerShell 获取从本周五开始的 12 个月的周五

Azure Runbook 在 Azure AD 中创建动态组

c# - 在IIS Web服务器上使用Powershell时访问被拒绝

windows - 在 Visual Studio 2019 的 PowerShell 窗口中找不到 ILDASM

azure - 无法在 Azure Functions v2 中运行 PowerShell 脚本

用于检查进程是否正在运行的 powershell 脚本

C# System.Management.Automation.Powershell 类在调用 Invoke() 时泄漏内存

powershell - 从多个扩展属性中选择一个属性

excel - Ping 脚本不导出结果

powershell - `PowerShellVersion` 和 `PowerShellHostVersion` 之间的区别