Link to home
Start Free TrialLog in
Avatar of namerg
namergFlag for United States of America

asked on

How to remove item with ForEach-Object

I have the following code
$FilesToDelete = get-childitem "C:\Scripts\PaperOut" -recurse | where-object {$_.mode -notmatch "d"} | where-object {$_.lastwritetime -lt "2/8/2018"} | Select name

Open in new window

But when i do
$FilesToDelete | For-EachObject Remove-Item -Path C:\Scripts\PaperOut\$._Name

Open in new window

I get this error:
Remove-Item : Cannot find path 'C:\Scripts\PaperOut\@{Name=1E31D2A9BEC949379D6E99F9D2305774.XFR}.Name' because it does not exist.
At line:1 char:36
+ ... te | ForEach-Object  { Remove-Item -Path C:\Scripts\PaperOut\$_.Name}
+                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Scripts\Pape...05774.XFR}.Name:String) [Remove-Item], ItemNotFoundException

Open in new window

I have not been able to get just the name. Thanks for your help
Avatar of Ben Personick (Previously QCubed)
Ben Personick (Previously QCubed)
Flag of United States of America image

Here you are fixed.

 The issue is you wrote $._ instead of $_.

$FilesToDelete | foreach {remove-item -Path "C:\Scripts\PaperOut\$_.Name"}

Open in new window

$FilesToDelete = get-childitem "C:\Scripts\PaperOut" -recurse | where-object {$_.mode -notmatch "d"} | where-object {$_.lastwritetime -lt "2/8/2018"} | Select name
$FilesToDelete | For-EachObject {Remove-Item -Path "C:\Scripts\PaperOut\$($_.Name)"}

Open in new window


You need a subexpression $() to evaluate a variable property inside a string.

Edit - sorry had some typos.
ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of namerg

ASKER

Thank you guys.