0

I am new to PowerShell and I have created the following code to delete specific files and folders:

$myFolderPath = "C:\Test"
$myLimit = (Get-Date).AddDays(-14)

# Delete files according to filter.
Get-ChildItem -Path $myFolderPath -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $myLimit} | Remove-Item -Force

# Delete empty folders.
Get-ChildItem -Path $myFolderPath -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

Is it possible to print out the full path of each item that will be removed to the console before the actual Remove-Item operation will be performed?

I guess sth. has to be added here....

... | Remove-Item -Force

and here...

... | Remove-Item -Force -Recurse

but I cannot find out how to implement that in an elegant way (without code duplication).

Rickson
  • 1,040
  • 2
  • 16
  • 40
  • 2
    I guess this is a badly edited copy of [how-to-delete-empty-subfolders-with-powershell](http://stackoverflow.com/questions/1575493/how-to-delete-empty-subfolders-with-powershell). What use has it to print folders when they are deleted anyway. Maybe you should take a look at the -whatif option of Remove-Item –  Nov 14 '16 at 18:05
  • I want to print them to the console to be able to see which folders in a huge tree have been deleted by the routine. – Rickson Nov 14 '16 at 18:19
  • Thank you to the hint to the -whatif option. But it is not what I need. – Rickson Nov 14 '16 at 18:45

2 Answers2

0

You can replace the remove-Item-Parts with

Foreach-Object { $_.fullname; Remove-Item -Path $_.Fullname (-Recurse) -Force}

LotPings comment might be better idea, if that is what you want.

Rickson
  • 1,040
  • 2
  • 16
  • 40
restless1987
  • 1,558
  • 10
  • 16
0

It does not get a lot of attention but Tee-Object could be a simple addition to the pipeline here. Redirect the output to a variable that you can print later.

...Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $myLimit} |
    Tee-Object -Variable removed | Remove-Item -Force
$removed | Write-Host

All of the file objects piped will be sent to $removed and then to Remove-Item. Since you have more than one delete pipeline you can also use the -Append parameter so that all files are saved in one variable if you so desired.

However this does not mean they were deleted. Just they made it passed the pipe. If you really wanted to be sure you should be using another utility like robocopy which has logging features.

Matt
  • 45,022
  • 8
  • 78
  • 119