1

I am using this command to remove multiple files in two different directories:

     Remove-Item -path c:\tmp\folder1\*, c:\tmp\folder1\* -Force -Recurse

both folders contain some zip files and sub folders which i want te remove

I need to check if those folders (folder1 and folder2) exist and not empty before executing this command. Can't figure it out :(

Any help would be appreciated.

5
  • Take a look at Get-ChildItem (learn.microsoft.com/en-us/powershell/module/…). Commented Mar 7, 2019 at 14:28
  • 1
    use Test-Path to see if the dir exists. do you really care if there is anything in the target dir? Commented Mar 7, 2019 at 14:28
  • @Lee_Dailey i am running this in ansible playbook so if the directory not exists the task will fail. Commented Mar 7, 2019 at 14:33
  • so you cannot use test-path inside the script? ///// you really ought to add that info to your OP - it seems to be an important part of the problem ... [grin] Commented Mar 7, 2019 at 14:43
  • If you can't use Test-Path for some reason I can't think of, you could simply ignore errors on folders that do not exist by writing Remove-Item -path c:\tmp\folder1\*, c:\tmp\DoesNotExist\* -Force -Recurse -ErrorAction SilentlyContinue. Of course this will also hide errors when there are files in there you may not delete because of lack of permissions.. Commented Mar 7, 2019 at 15:01

2 Answers 2

2

If you want to check multiple conditions with an if then -and the results:

if ((Test-Path 'C:\tmp\folder1\*') -and 
    (Test-Path 'C:\tmp\folder2\*') ){
    Remove-Item -path c:\tmp\folder1\*, c:\tmp\folder1\* -Force -Recurse
} else {
    "not all conditions met."
}

An explicit Test-Path for the folders isn't neccessary as it is implied with items in the folders.

Sign up to request clarification or add additional context in comments.

Comments

1

I suggest using the command "test-path", and then using a | (a pipe) to output a true or false value for proceeding to executing the command that you are using to delete a directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.