Removing a folder on a network share RRS feed

  • Question

  • Hello,

    I am looking at removing a lot of users personal directories which have not been used in over 5 years as part of a tidy up. My question / fear is that if I use the remove-item -recurse that it will remove more than I want it to.

    I have the following which I may need to tweak a little as I would like it to delete the folder as well as its sub directories.

    As an example: 

    \\server\Folder1\UsersFolder1\Lots of other folders and files

    \\server\Folder1\UsersFolder2\Lots of other folders and files

    I want to remove folder UsersFolder1 and everything inside it. So my fear is when I pass \\server\Folder1\UsersFolder1 as the path and it doesn't exist it (Which it should as I pull this information from AD prior) will delete the contents of \\server\Folder1 which obviously I dont want. 

    I am currently using Remove-Item $SomeVariable -Recurse to do this but I wanted to be sure that if the directory didn't exist it would just error and move to the next line in the code.

    If it does exist that it would delete everything inside UsersFolder1 and the UsersFolder1 itself and nothing more.

    I hope this makes some sense.



    • Moved by Bill_Stewart Thursday, January 25, 2018 9:56 PM Unanswerable drive-by question
    Friday, October 20, 2017 2:42 PM

All replies

  • Recurse will only begin from the directory that you specify and it will always recurse down the directory path, not up.

    So, your fear of it somehow deleting Folder1 is unnecessary.

    I would recommend to you though that you create some dummy data on your local disk (or a test share) to go through the logic of your script.  This is usually what I do in the event that I mess up some logic, especially when dealing with deletions.

    Syst3m32 https://www.sysadminsoup.com

    Friday, October 20, 2017 2:47 PM
  • I think -whatif can be of somehelp here which will not actually perform the task but show what is going to happen

    also you have to test a folder on your local computer. make it shared and access it \\localcomputername 

    then try to create a script

    Thanks & Regards Ramandeep Singh

    Sunday, October 22, 2017 3:02 AM
  • Thank you for your replies

    How do I get it to remove the parent folder as well so in the example above this would be UsersFolder1?



    Thursday, October 26, 2017 8:39 AM
  • That is not a folder.  It is the share and can only be removed by removing the share.


    Thursday, October 26, 2017 8:43 AM
  • Hi Sorry the example shows it as a share (I didn't spot that!) in reality it would be the folder though.



    Friday, October 27, 2017 1:08 PM
  • You would have to remove the share first.


    Friday, October 27, 2017 1:10 PM
  • To remove only subfolders

    Remove-Item \\system\share\folder -Force


    Friday, October 27, 2017 1:11 PM