powershell - 来自流的 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"
}
}
解决方案
我会说你应该阅读这篇文章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"
}
}
试一试,让我知道它是否有效。
更新: 更新以反映仅包含工作解决方案的代码。
推荐阅读
- wordpress - 带有简码的前端的 Wordpress 类别描述
- javascript - 是否有为 IE11 设置 babel/webpack 的简单来源?
- javascript - 通过Javascript更改元素的显示?
- osgi - OSGI 导入包问题
- r - 关于 forvalues 的等效命令
- ruby-on-rails - 在 Rails 中集成 CKEditor 自动链接插件
- c++ - 如何反转二叉搜索树?
- java - java.util.concurrent.ExecutionException:com.android.builder.internal.aapt.v2.Aapt2Exception:Android资源链接失败flutter_youtube
- elasticsearch - 重新索引和更新连接字段
- php - 在 WordPress 中使用 add_shortcode() 在主页中创建内容部分