首页 > 解决方案 > 来自流的 PowerShell 读取行

问题描述

使用 PowerShell 脚本,我将不得不读取和写入控制台。我们写一个输入并等待一个将被捕获的输出$Reader.ReadLine()。但是在某些情况下,不会为读者捕获任何输出,在这种情况下,读者需要查看流中的数据,如果没有数据,则会ReadLine()卡住/阻塞等待来自控制台流的数据,而我们需要ReadLine()只需等待 5 秒钟。如果没有数据,则需要超时并继续执行下一个命令。

请让我知道是否有任何方法可以$Reader.ReadLine()在 PowerShell 中超时?

我看到在 Java/C# 中我们可以使用$Reader.ReadLine(1000)1 秒后超时,但这似乎不适用于 PowerShell。

$tcpConnection = New-Object System.Net.Sockets.TcpClient($Computername, $Port)
$tcpStream = $tcpConnection.GetStream()
$reader = New-Object System.IO.StreamReader($tcpStream)
$writer = New-Object System.IO.StreamWriter($tcpStream)
$writer.AutoFlush = $true

$buffer = New-Object System.Byte[] 1024
$encoding = New-Object System.Text.AsciiEncoding 

while ($tcpStream.DataAvailable) {
    $reader.ReadLine()
}
if ($tcpConnection.Connected) {
    $writer.WriteLine($username)
    $reader.ReadLine()
    $writer.WriteLine($password)
    $reader.ReadLine()

    try {
        # if there is any data it will show here if there is no data then
        # it should get timed out after 5 seconds
        $Reader.ReadLine()
    } catch {
        Write-Host "Login Failed"
    }
}

标签: powershell

解决方案


我会说你应该阅读这篇文章C# Stream.Read with timeout

将其转换为您的代码示例,最终应该是这样的。

$tcpConnection = New-Object System.Net.Sockets.TcpClient($Computername, $Port)

#This is one way you could try
$tcpConnection.ReceiveTimeout = 5000;

$tcpStream = $tcpConnection.GetStream()
$reader = New-Object System.IO.StreamReader($tcpStream)

$writer = New-Object System.IO.StreamWriter($tcpStream)
$writer.AutoFlush = $true

$buffer = New-Object System.Byte[] 1024
$encoding = New-Object System.Text.AsciiEncoding 

while ($tcpStream.DataAvailable) {
    $reader.ReadLine()
}
if ($tcpConnection.Connected) {
    $writer.WriteLine($username)
    $reader.ReadLine()
    $writer.WriteLine($password)
    $reader.ReadLine()

    try {
        # if there is any data it will show here if there is no data then
        # it should get timed out after 5 seconds
        $Reader.ReadLine()
    } catch {
        Write-Host "Login Failed"
    }
}

试一试,让我知道它是否有效。

更新: 更新以反映仅包含工作解决方案的代码。


推荐阅读