PowerShell 5.1中Read-Host调用前输出不显示的问题咨询
PowerShell中直接输出对象延迟显示的问题解析及解决
问题原因
在PowerShell 5.1中,成功输出流(默认的对象输出)采用缓冲机制:脚本执行时,PowerShell会先将输出对象暂存到缓冲区,直到脚本执行完毕、缓冲区填满,或者遇到强制刷新操作时,才会把内容输出到控制台。
Read-Host是阻塞式命令,会暂停脚本执行等待用户输入,此时$sorted对象还留在输出缓冲区中,没有被立即刷新到控制台,因此要等你输入选择项、Read-Host执行完成后,缓冲区的内容才会一次性显示出来。
而Write-Host是直接写入控制台的宿主UI流,不经过成功流的缓冲处理,所以能实时显示内容。
解决方法
要让$sorted的内容立即显示,只需强制将输出对象写入控制台,绕过缓冲机制,最直接的方式是使用Out-Host命令:
修改脚本中输出列表的行:
# 替换原来的 $sorted 为以下内容 $sorted | Out-Host
修改后的完整脚本:
$name = read-host "name?" # The search string # Grab everything that matches the partial string $searchlist = dir -recurse -filter "*$name*" | select FullName # Create an empty array $searchtable = @() $number = 0 # Assign a number for each file to ease selection $searchlist | foreach { $number++ $o = [PSCustomObject]@{ Number = $number Name = $_.FullName } $searchtable += $o } # Ensure the returned list is sorted by number $sorted = $searchtable | sort Number # 强制输出到控制台,避免缓冲延迟 $sorted | Out-Host $selectedvid = read-host "which one?" $vid = $searchtable | where {$_.number -eq $selectedvid} | select -ExpandProperty Name invoke-item -literalpath $vid
补充说明
在PowerShell 7及以上版本中,交互式场景下的输出缓冲机制做了优化,默认会实时显示对象输出,不会出现这种延迟问题,但PowerShell 5.1仍保留旧的缓冲逻辑。
内容的提问来源于stack exchange,提问作者Nic
相关产品推荐
相关产品推荐

