namerg
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
But when i do$FilesToDelete | For-EachObject Remove-Item -Path C:\Scripts\PaperOut\$._Name
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
I have not been able to get just the name. Thanks for your help
$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)"}
You need a subexpression $() to evaluate a variable property inside a string.
Edit - sorry had some typos.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you guys.
The issue is you wrote $._ instead of $_.
Open in new window