简体   繁体   中英

Powershell script to delete folders from list

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 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM