Friday, January 20, 2012

How to use –Exclude switch in Remove-Item cmdlet in PowerShell


Hi,
today i was trying to remove some junk folders and files in a  specific folder. But i don’t want to remove all of file and folder , i want to keep few folders. Then i think that i should use the –Exclude switch with Remove-Item Cmdlet.
I tried to use –Exclude switch but somehow i failed to get it working because i don't know the exact patter used by –Exclude switch. After few minutes of testing i get it done and i thought i should share this tip with you.
  1. $Lenovo = "D:\P-Temp\Lenovo\*"
  2. Remove-Item -Recurse  -Path $Lenovo -Exclude system,temp,updates.ser,"*.xml"   -VerboseForce
In $Lenovo variable i specified the folder path in which I want to remove the items
I want to Exclude folder name “System”,”temp” and file name “updates.ser” and all .XML Files
in -Exclude switch give the folder name which you don’t want to delete,  no need to put the in a double quotes “” in folder name . You can provide multiple folder name separated by comma.
in pattern matching make sure you put the wild cards in double quotes “”.

Lets Test it !!
see we have System,Temp, few XML and one Updates.Ser file which we exclude to deleted. lets run the script now and see which file is getting deleted.
20-01-2012 12-48-32
after running the script .
All folders are stay intact which we exclude in the Remove-Item cmdlet.
20-01-2012 12-52-56
I hope that i helps someone .
thanks
aman dhally


2 comments:

  1. I have no idea about this topic. Your post helped a lot in understanding the basic of this function. I just followed the steps given in this post. I think to be formal with it I need to apply this several times. Thanks for the post.
    electronic signature

    ReplyDelete
  2. Your script is not working. If you have files inside system and temp folder they are removed.

    ReplyDelete