How to judge certain type of files(suce as csv file) exist using powershell?
-
30-05-2021 - |
题
I need a function to delete all the csv files in a folder A, if there is csv files in folder A , then delete all the csv files(actually, I don't know the exact csv files' name in folder A); if there is no csv file in folder A , then do nothing. I have searched a topic about removing mp3 files: Powershell - Delete all non mp3 files
then I take the example out and below is the cmdlet that delete my csv files in folder A :
Get-childitem -Recurse | Where-Object {$_.Extension -eq '.csv'} |
Remove-Item -whatIf
but there is a problem , when there is no csv files in folder A , when excuting above cmd will cause error. I just don't know how to judge if csv file exists, anyone else can help? thx very much.
解决方案
You can simply add -ErrorAction
to remove-item
to skip the error:
Get-childitem -Recurse | Where-Object {$_.Extension -ne '.csv'} |
Remove-Item -ErrorAction SilentlyContinue
其他提示
Use an if construct to test if a condition is true before executing the deletions:
if(gci c:\folderA -filter *.csv){do-something}
If the statement between the parentheses returns false, the code between the curly braces is not executed.