2015-10-18 60 views
-3

我想要除了以.txt結尾的文件以外的所有文件。返回除.txt之外的所有文件

foreach ($file in Get-ChildItem $Out | Where $file.Extension -ne .txt) { 

Write-Host $file.name 

} 

這列出了包括.txt在內的所有項目。

這應該是什麼樣子?

+3

這是哪一種語言?某種類型的shell腳本?您應該將其添加到問題中,並可能相應地標記它。 –

回答

2

沒有必要爲一個循環做到這一點,只是:

Get-ChildItem | Where-Object { $_.Extension -ne ".txt" } Select-Object "Name" 

或者:

Get-ChildItem -Exclude "*.txt" | Select-Object "Name" 

如果你堅持一個循環,或者需要的東西,你可以:

foreach ($file in Get-ChildItem -Exclude "*.txt") { Write-Host $file.Name; } 

foreach ($file in Get-ChildItem | Where-Object { $_.Extension -ne ".txt" }) { Write-Host $file.Name; } 

foreach ($file in Get-ChildItem | Where-Object Extension -ne ".txt") { Write-Host $file.Name; } 

從問題的例子不工作,因爲$file只能foreach

+0

謝謝。有用。但是你有什麼想法,爲什麼我的代碼不起作用? – user3019059

+0

如果你使用'Where',你需要寫出你的條件不一樣。檢查所有選項[文檔](https://technet.microsoft.com/library/hh849715.aspx)。 – Jeroen

+0

@ user3019059你的工作不起作用,因爲'$ file'直到大括號{}'內的foreach代碼塊才存在。在這之前,你不能在foreach循環中使用'$ file.Extension'。它必須是'foreach($文件中(Get-ChildItem $ Out | Where Extension -ne'.txt')){...}' – TessellatingHeckler

相關問題