0

To piggyback onto this question, PowerShell script to delete files from list and output list of deleted file, I am trying to accomplish something similar. I have a list of usernames that match the names of some folders on our network file server. Not all of the usernames in the list are going to have home folders created, some may simply not exist.

My psuedocode looks something like this:

  • Load the list of users
  • For each user check to see if they have a directory or not
  • If they have a directory, forcefully and recursively remove it

Here is some code that I have been working unsuccessfully with:

$Termed_Users = "C:\Data\Termed_Users.csv" 
$Home_Folders = "X:"

$UserList = Import-Csv $Termed_Users

$UserList | ForEach-Object {    
   $ID = $_.ID  
   $User_Home = $Home_Folders + "\" + $_.ID }

If ( Test-Path $User_Home ) { Remove-Item -Recurse -Force $User_Home }
1
  • It does not throw any errors and it does not delete the folders. I am not sure. Commented Feb 15, 2012 at 21:55

1 Answer 1

3

The issue is in your ForEach-Object pipe.

You are continually reassigning the $User_Home variable, and cycle through the whole list before attempting any deletes. Move your deletion into that script block:

$UserList | ForEach-Object {    
   $ID = $_.ID  
   $User_Home = $Home_Folders + "\" + $_.ID
   Remove-Item -recurse -force $User_Home -erroraction silentlycontinue }

I also removed the test since it won't matter - you will try to delete them all and ignore the errors.

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

2 Comments

That is both fancy and novel. I just tested it and it works really well! Thank you so much for your help.
@John - you'll learn lots of fancy powershell tricks as you keep going. happy to help!

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.