gpt4 book ai didi

powershell - 如何从 Get-Content -Wait 进行管道传输?

转载 作者:行者123 更新时间:2023-12-02 19:49:31 32 4
gpt4 key购买 nike

我想将 Get-Content $file -Wait 的输出通过管道传输到自定义 PowerShell 脚本。脚本看起来像这样。

$lines = ($input | Out-String) -replace "`r", "" -split "`n"

foreach ($line in $lines) {
#Process $line

Write-Host $line
}

基本上,这个想法是获取输入,对其进行良好的格式化,然后在将输出打印到控制台之前对其进行处理。

问题是当我像 cat $file -Wait | 这样调用它时,没有任何内容发送到我的脚本。 MyScript。如果我执行 cat $file -Waitcat $file | MyScript,一切都按预期工作。但是将管道和等待参数结合起来不起作用。

我需要使用一些语法来允许处理 -Wait 参数吗?我尝试使用 Out-String -Stream,但这也不起作用。

最佳答案

问题出在 $input 上。

如果你这样做:

Get-Content $file -Wait | Get-Member -InputObject $input

或者

Get-Content $file -Wait | Get-Member -InputObject $_

您将得到:

Get-Member : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

如果 Get-Member 无法读取通过管道的对象,您就知道该对象(或管道)出现了严重问题。

让我们尝试将 $input 通过管道传输到 Out-String,就像您在脚本中所做的那样:

Get-Content $file -Wait | Out-String $input

您将得到:

Out-String : A positional parameter cannot be found that accepts argument 'System.Collections.ArrayList+ArrayListEnumeratorSimple'.
At line:1 char:52
+ get-content '.\netstat anob.txt' -wait | Out-String <<<< $input
+ CategoryInfo : InvalidArgument: (:) [Out-String], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.OutStringCommand

所以,事实上,“Get-Content”-Wait 给了你一种奇怪的对象:一个 System.Collections.ArrayList+ArrayListEnumeratorSimple 。它看起来像是 System.Collections.ArrayList 对象或类似对象的 GetEnumerator() 方法的结果。

鉴于 Get-Member 甚至“Get-Member -Force”无法读取这种“对象”,从 Powershell 的角度来看,它不是一个对象。

解决方法是从 Get-Content 中删除 -Wait 参数,并找到另一种方法来实现您想要的效果,可能是通过运行 Get-Content,然后循环运行几次“Get-Content -Tail 1” .

关于powershell - 如何从 Get-Content -Wait 进行管道传输?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25571460/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com