tags:

views:

148

answers:

2

I've got a weird thing going here in Powershell 1.0 and I don't understand why Powershell is reacting the way it is.

Situation: I've created several zip files on a drive by the letter e:

Now I want to delete them all. But there are more zip files on my e: drive. So I want to delete only the ones in this specific folder and its subfolders.

The command I want to use for this is:

PS E:\> Get-ChildItem -Path E:\Webdev\icons\ -Include *.zip -Recurse -Name -Force | Remove-Item -Force

However, upon execution, I get a bunch of error's, all saying that

Cannot find path E:\test.zip because it does not exist.

Indeed, there is no such file as test.zip directly under e: It does exist under the icons folder which I handed the script.

The solution is for me to change directory to the icons folder and execute the command there.

But this is not logical. I want be able to say in which directory the files should be deleted and then they should be deleted only there. Why Powershell starts looking for the files in the current directory is a mystery to me.

Can anybody explain this to me please?

+3  A: 

Get-ChildItem seems to return the portion of the path following the search path plus the filename when using -Name. This filename is then piped into Remove-Item which is using the current directory plus the filename returned.

I tried that command using -FullName but that doesn't seem to work so you should be able to pipe that command into Select-Object to specify the fullname and pipe that into Remove-Item.

Try:

    Get-ChildItem -Path E:\Webdev\icons -Include *.zip -Recurse | 
Select-Object -Property FullName | Remove-Item -Force
Arnold Spence
+8  A: 

If you remove the Remove-Item at the end of the pipeline you will see that all path names that are returned are relative to the path you entered via the -Path parameter to Get-ChildItem. So Remove-Item looks in the current directory for all paths Get-ChildItem returns.

As capar suggested, the -Name parameter is the problem here. Dropping it ensures that you get File objects where Remove-Item can locate the file easily:

Get-ChildItem -Path E:\Webdev\icons\ -Include *.zip -Recurse -Force | Remove-Item -Force

will work as intended. Don't get down to string level if you can solve something with objects :-)

Joey
+1, That does indeed seem to work, and simpler than my solution
Arnold Spence
thanks, that did the trick. Odd how that specific parameter influences the outcome somuch.
WebDevHobo
Well, the parameter tells the cmdlet to return strings instead of FileInfo objects. Remove-Item is smart enough to find out what to remove when getting a FileInfo but with strings it can only assume a pathname ... and since those are relative to the path you specified ... it can only guess. The -Name parameter is probably only there for display purposes; using objects is much easier in a pipeline, though.
Joey
My mantra, stop thinking in text.
JasonMArcher