gpt4 book ai didi

command-line - 使用 [Console]::ReadLine() 时未收到通过管道传输到 PowerShell.exe 的文本

转载 作者:行者123 更新时间:2023-12-04 04:15:15 40 4
gpt4 key购买 nike

我在调用 .NET 时出现间歇性数据丢失 [Console]::ReadLine()读取管道输入到 PowerShell.exe。在 CMD 中,运行:

>ping localhost | powershell -NonInteractive -NoProfile -C "do {$line = [Console]::ReadLine(); ('' + (Get-Date -f 'HH:mm:ss') + $line) | Write-Host; } while ($line -ne $null)"23:56:45time<1ms23:56:4523:56:46time<1ms23:56:4623:56:47time<1ms23:56:4723:56:47

Normally 'ping localhost' from Vista64 looks like this, so there is a lot of data missing from the output above:

Pinging WORLNTEC02.bnysecurities.corp.local [::1] from ::1 with 32 bytes of data:Reply from ::1: time<1ms Reply from ::1: time<1ms Reply from ::1: time<1ms Reply from ::1: time<1ms Ping statistics for ::1:    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),Approximate round trip times in milli-seconds:    Minimum = 0ms, Maximum = 0ms, Average = 0ms

But using the same API from C# receives all the data sent to the process (excluding some newline differences). Code:

namespace ConOutTime {
class Program {
static void Main (string[] args) {
string s;
while ((s = Console.ReadLine ()) != null) {
if (s.Length > 0) // don't write time for empty lines
Console.WriteLine("{0:HH:mm:ss} {1}", DateTime.Now, s);
}
}
}
}

输出:

00:44:30 Ping WORLNTEC02.bnysecurities.corp.local [::1] 从::1 与 32 字节的数据:
00:44:30 来自::1的回复:时间<1ms
00:44:31 来自::1的回复:时间<1ms
00:44:32 来自::1的回复:时间<1ms
00:44:33 来自::1的回复:时间<1ms
00:44:33::1 的 Ping 统计信息:
00:44:33 数据包:发送 = 4,接收 = 4,丢失 = 0(0% 丢失),
00:44:33 大约以毫秒为单位的往返时间:
00:44:33 最小值 = 0ms,最大值 = 0ms,平均值 = 0ms

因此,如果从 PowerShell 而不是 C# 调用相同的 API,则 StdIn 的许多部分都会被“吃掉”。即使我没有使用“PowerShell.exe -Command -”,PowerShell 主机是否也在从 StdIn 读取字符串?

最佳答案

您可以使用 $input PowerShell 中的枚举器以访问通过管道传输到程序中的数据。我也发现 [Console]::ReadLine()不知何故,几乎没有。不过原因不明。

C:\Users\Me> ping localhost | powershell -noninteractive -noprofile -c "$input|%{(date -f HH:mm:ss)+' '+$_}"

07:31:54
07:31:54 Pinging Sigmund [::1] with 32 bytes of data:
07:31:54 Reply from ::1: time<1ms
07:31:54 Reply from ::1: time<1ms
07:31:54 Reply from ::1: time<1ms
07:31:55 Reply from ::1: time<1ms
07:31:55
07:31:55 Ping statistics for ::1:
07:31:55 Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
07:31:55 Approximate round trip times in milli-seconds:
07:31:55 Minimum = 0ms, Maximum = 0ms, Average = 0ms

C:\Users\Me>ping localhost

Pinging Sigmund [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms

Ping statistics for ::1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

关于command-line - 使用 [Console]::ReadLine() 时未收到通过管道传输到 PowerShell.exe 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2902077/

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