12
我想使用powershell腳本迭代文件夾中的文件;如何使用PowerShell遍歷文件?
我想使用powershell腳本迭代文件夾中的文件;如何使用PowerShell遍歷文件?
Get-ChildItem | ForEach-Object { <# do what you need to do #> }
或更短:
gci | % { <# ... #> }
,或者如果你想要一個明確的循環結構:但是
foreach ($file in Get-ChildItem) {
# ...
}
注意,這foreach
將只運行一次,從Get-ChildItem
所有輸出被收集。在我看來,大多數Powershell代碼應該儘可能使用管道。
如果您有大量文件,請使用[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
@TamusJRoyce:Get-ChildItem也應該流。與Directory.GetFiles相反,當然,它返回一個數組。 – Joey 2017-06-29 12:37:27