Tuesday, September 7, 2010

Remove-Item –recurse will actually make you curse

Walking in today, I found myself with a challenge.  Definitely not a unique one, but a challenge.  I have to delete an .xls template from a file server within many different project folders.  Our setup looks like this: \\server\Projects\{JobNumber}\*.  Within each job number are many different folders and sub-folders.  I’ve been tasked to remove the old excel template that we were using and replace it with the new one.

Sounds like a job for PowerShell eh?  I’ve done some recursion in the past using VBScript and I’d rather not revisit that…  It was a bit of torture to get the logic sorted out using that language.  With PowerShell, you just slap a –recurse to what you are doing and you *should* be good to go. Or so you thought…  A quick ping to Bing showed me the Remove-Item cmdlet usage doc on TechNet.  Reading over this, it seems very easy to setup recursion and manipulate files, until you do something like this:

   1:  $path = "c:\test\*"


   2:   


   3:  Remove-Item $path -recurse -include .xls






These simple lines of code simply fail without any notification or errors.  I’ve sent a tweet out to the Scripting Guys to get a reason why.  I haven’t heard back from them so far, but all is not lost!  You simply have to think outside the box.  To get this to work you have to use these lines of code instead:




   1:  $path = "c:\test\*"


   2:   


   3:  Get-ChildItem $path -recurse -include *.xls | Remove-Item






This works consistently and will give you the results you’d expect.  I’ll update this article if I hear back from the Scripting Guys ;-).



2010-09-07 11:10 a.m. Update:  As always the Scripting Guys are awesome and answer my question.  Take a look at their response.

2 comments:

Trevor Sullivan said...

Of course, if you're doing something recursively like this, you'll probably want to ensure that you're:

1) Logging what you're doing
2) Making a backup copy of the files you're modifying or deleting

Matt B. said...

Good point Trevor. I try to make my code samples easy to follow, so the point I'm trying to make doesn't get lost in the translation. With that in mind, this and any other code sample is a simplified excerpt of what I'm really doing unless noted.

Thanks for the tips! I'm sure they'll add value to whomever comes across this post.