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

时间:2014-08-29 15:28:50

标签: powershell wait pipeline

我想将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,但这也不起作用。

4 个答案:

答案 0 :(得分:2)

问题在于$ 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”

答案 1 :(得分:2)

如果您的脚本接受管道输入,则可以这样做。您可以在管道到Select-String等其他cmdlet时看到它。例如,将script.ps1定义为:

process { Write-Host "line: $input" }

然后运行

1..200 | foreach { add-content -Path test.txt -Value "$_"; start-sleep 1 }

在一个PowerShell会话中

gc test.txt -wait | .\script.ps1

在另一个中,您可以看到每一行都通过管道传输到脚本。

答案 2 :(得分:1)

我认为没有办法做你要问的事。 -Wait启动一个永不停止的循环,唯一停止的方法是手动杀死它。因为它总是卡在循环中,所以你在启动循环后尝试做的任何事情都不会进行处理。

答案 3 :(得分:0)

问题出在这一行:

Write-Host $line

您应该使用Write-Output。 Write-Output将对象发送到管道,Write-Host直接发送到主机(控制台)。

相关问题