Pages

Wednesday, September 8, 2010

Delete files using a CSV file as an input and the remove-item command

Deleting mass amounts of files is easy in PowerShell.  Using the Remove-Item command you can set up a CSV file to feed a list of files and their locations to the command-let and step down the list, deleting as you go.

The basic structure of the command would look like this:


$data = import-csv c:\file_inventory\deletelist.csv

foreach ($line in $data)

{

$A= $($line.fullname)
remove-item $a -recurse -force

}
To break down what's going on above:
  • The $data variable is going to hold the information that's contained in the deletelist.csv file.  Presumably this file will contain the paths and names of the files to be deleted.
  • The FOREACH statement is stepping thru the deletelist.csv file and then feeding the data to the loop below.  The script will then step thru the loop until it gets to the end of the data file.
  • The loop itself contains only two things:
    • $A=$($line.fullname) - let's make $a contain the information contained in the current line in the CSV file we're stepping thru.  $($Line.Fullname) says: grab the information in the current $line of the $data and look in the fullname column. 
    • Remove-Item is equivalent to the DOS DEL command, however you can feed it a variable (in this case $a).
    • Recurse - step thru any folders below the folder your in.  This is used in case a folder has subfolders that will also be deleted.  If this switch is not there, then the script will stop and ask you what to do.
    • Force - Delete the file even if it's read only, hidden etc.
  • If you want to test the above scenario you can use the -whatif switch in the remove-item statement, this will make PowerShell just show you what would have happened if you ran the command.