Reputation: 25373
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:
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 }
Upvotes: 0
Views: 9776
Reputation: 65197
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.
Upvotes: 3