KdgDev
KdgDev

Reputation: 14529

Powershell problem with internal logic

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?

Upvotes: 1

Views: 799

Answers (2)

Joey
Joey

Reputation: 354586

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 :-)

Upvotes: 8

Arnold Spence
Arnold Spence

Reputation: 22272

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

Upvotes: 3

Related Questions