Reputation: 411
I have script that selects .exe
files with the specified name from the local folder and removes all files, except first.
$P
variable is defined in param
.
$P ="$($env:USERPROFILE)\Desktop\I"
Then I got this error
$C = Get-ChildItem $P -Filter *.exe| Where-Object Name -Like '*r_2-2*' | Sort-Object Name -Descending | Select-Object -ExpandProperty Name -Skip 1 | Remove-Item
Remove-Item : Cannot find path 'D:\FM\r_2-2.exe' because it does not exist.
At line:1 char:251
+ ... Descending | Select-Object -ExpandProperty Name -Skip 1 | Remove-Item
I know about foreach
loop but want to use For-EachObject
cmdlet instead.
Upvotes: 0
Views: 1415
Reputation: 3350
You can make the use of FullName
parameter directly in your statement. Try this -
$C = Get-ChildItem $P -Filter *.exe| Where-Object Name -Like '*r_2-2*' | Sort-Object Name -Descending | Select-Object -ExpandProperty FullName -Skip 1
$c | ForEach-Object {Remove-Item -Path $_}
Use -Force
parameter if you want to delete the hidden files too.
Upvotes: 1
Reputation: 17347
You were quite close, if you want to use ForEach-Object
:
Get-ChildItem $P -Filter *.exe | Where-Object Name -Like '*r_2-2*' | Select-Object -Skip 1 | ForEach-Object { remove-item $_.FullName -force }
To skip one first found result just Select-Object -Skip 1
is enough.
Remove-Item -Force
also removes hidden and read-only files.
Upvotes: 1