locked
How to answer "No" to confirmation prompt on deletion of a folder? RRS feed

  • Question

  • I try to write a PS script, which will browse through the folder3 and delete child files and folders, if their CreationTime and LastWriteTime are older, than 1 month:

    ls -r -force 'd:\folder1\folder2\folder3' | where {($_.fullname -like '*:\*\*\*\*') -and ($_.creationtime -le (get-date).addmonths(-1)) -and ($_.lastwritetime -le (get-date).addmonths(-1))} | sort -desc fullname | rm -force

    How'd I answer "No" to all the confirmations it asks, when the folder is not empty? I only need folder deletion if it's empty.

    "-Confirm:$False" or "-ErrorAction SilentlyContinue" statements do not help.


    • Edited by dvb15 Thursday, March 28, 2019 7:56 AM
    Thursday, March 28, 2019 6:22 AM

Answers

  • Hi,

    Thanks for your question.

    If you want to delete the empty folders, you can follow the example below:

    Get-ChildItem -Path c:\temp\ -Force -Recurse -Directory | Where-Object {(Get-ChildItem $_.FullName -Force).count -eq 0} | rm -Force 

    Best regards,

    Lee


    Just do it.

    • Marked as answer by dvb15 Thursday, March 28, 2019 9:58 AM
    Thursday, March 28, 2019 9:01 AM

All replies

  • You will have towrite code to accomplisg what you are asking.  There is not CmdLet that can do what you ask.


    \_(ツ)_/


    • Edited by jrv Thursday, March 28, 2019 8:04 AM
    Thursday, March 28, 2019 8:04 AM
  • Hi,

    Thanks for your question.

    If you want to delete the empty folders, you can follow the example below:

    Get-ChildItem -Path c:\temp\ -Force -Recurse -Directory | Where-Object {(Get-ChildItem $_.FullName -Force).count -eq 0} | rm -Force 

    Best regards,

    Lee


    Just do it.

    • Marked as answer by dvb15 Thursday, March 28, 2019 9:58 AM
    Thursday, March 28, 2019 9:01 AM
  • Lee's code will not work as it can leave empty folders after one pass. It must be run recursively until there are no more empty folders.


    \_(ツ)_/

    Thursday, March 28, 2019 10:21 AM