Powershell Get-ChildItem输出延迟了吗?

时间:2016-07-26 21:13:08

标签: powershell

下面的Powershell版本信息:

Name                           Value
----                           -----
PSVersion                      5.0.10586.494
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.10586.494
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

我有以下powershell代码:

Write-Host "Step 1..."

$find = "string-to-find"

Get-ChildItem -Path D:\path\path\ -Include *.dat1, *.dat2, *.dat3, *.dat4, -Recurse `
 | Select-String -SimpleMatch $find `
 | Select-Object -Unique Path

Write-Host "Step 2 ..."

输出:

Step 1...

Step 2...

Path
----
D:\path\path\test.dat1

基本上,Get-ChildItem的输出发生 AFTER 后续的Write-Host声明 - 为什么????

鉴于此代码在以前的版本中运行良好 - 应该使用正确的输出方法,以便按照执行顺序显示输出?

提前致谢。

仍然尝试使用以下方法使其工作:

Get-ChildItem -Path D:\path\path\ -Include *.dat1, *.dat2, *.dat3, *.dat4, -Recurse `
 | Select-String -SimpleMatch $find `
 | Select-Object -Unique Path `
 | ForEach-Object { $_ } | Write-Host

但输出如下:

@{Path=D:\path\path\something.dat1}
@{Path=D:\path\path\something.dat1}

我想要的只是列出的完整路径名(就像它在v5之前工作一样)。

2 个答案:

答案 0 :(得分:1)

旧问题,但请添加我的答案,因为它是Google的最佳搜索结果之一。

如果您要继续使用Write-Host,例如由于其着色功能,可以通过显式地传递到Format-Table来完成。完整的代码为:

Write-Host "Step 1..."

$find = "string-to-find"

Get-ChildItem -Path D:\path\path\ -Include *.dat1, *.dat2, *.dat3, *.dat4, -Recurse `
 | Select-String -SimpleMatch $find `
 | Select-Object -Unique Path `
 | Format-Table

Write-Host "Step 2 ..."

Get-ChildItem(和类似的命令)或没有以变量\ file结尾的管道,最后通过对Write-Output的隐式调用输出到控制台。

控制台输出显示为乱序,因为Write-Output不会同步写入控制台,除非您在Write-Output上显式调用Format-Table。

参考:
https://serverfault.com/questions/693549/powershell-write-host-not-synchronous
https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/14925213-bug-console-output-appears-out-of-order

答案 1 :(得分:0)

解决 - 改变所有"写主机"到"写输出"根据这篇文章:jsnover.com/blog/2013/12/07/write-host-considered-harmful

相关问题