2010-08-31 129 views

回答

15
Get-ChildItem | ForEach-Object { <# do what you need to do #> } 

或更短:

gci | % { <# ... #> } 

,或者如果你想要一个明确的循环结构:但是

foreach ($file in Get-ChildItem) { 
    # ... 
} 

注意,这foreach将只运行一次,从Get-ChildItem所有输出被收集。在我看来,大多数Powershell代码应该尽可能使用管道。

+0

如果您有大量文件,请使用[System.IO.Directory] ​​:: EnumerateFiles。它需要.NET 4+。但它不会等到它遍历所有文件。如果在一个目录中有成千上万,这是一个问题。 https://stackoverflow.com/questions/14970692/powershell-io-directory-find-file-types-in-all-subdirectories – TamusJRoyce 2017-06-28 14:41:59

+0

@TamusJRoyce:Get-ChildItem也应该流。与Directory.GetFiles相反,当然,它返回一个数组。 – Joey 2017-06-29 12:37:27