How do I move a file to the Recycle Bin using PowerShell?
Asked Answered
D

8

61

When using the rm command to delete files in Powershell, they are permanently deleted.

Instead of this, I would like to have the deleted item go to the recycle bin, like what happens when files are deleted through the UI.

How can you do this in PowerShell?

Debase answered 2/2, 2009 at 1:47 Comment(1)
Once you've picked a solution below, you can update the rm alias to use it via Set-Alias rm Remove-ItemSafely -Option AllScopeFluellen
D
19

Here is a shorter version that reduces a bit of work

$path = "<path to file>"
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete")
Debase answered 2/2, 2009 at 16:14 Comment(1)
This asks with confirmation window.Importunity
A
43

2017 answer: use the Recycle module by Brian Dukes

Install-Module -Name Recycle

Then run:

Remove-ItemSafely file

I like to make an alias called trash for this.

Apple answered 1/2, 2017 at 17:28 Comment(11)
What if there are multiple files?Pantsuit
@KahnKah Use .\* instead of file but this will delete all subdirectories tooZosima
@Neonit yes that's the same with all third party software.Apple
@Apple Yes, but this command looks very much like there is no third party involved and comes from Microsoft instead as there is no URL or anything given that would suggest it's from a public repo.Newman
How is this better than the VB solution? That doesn't require installing 3rd party modules.Cards
@Cards it doesn't require learning/using a separate language.Apple
@Apple neither does the VB solution. Just copy-paste it.Cards
@Cards Most people using Powershell don't want to see code in a separate language in the middle of their Powershell scripts.Apple
It should be noted that the author of this Module is Brian Dukes with Copyright (c) 2016 Engage Software. It is not an official Microsoft Module.Livialivid
@Livialivid that is true, but I think most software developers understand that modules downloaded from online package providers like PS Gallery, npm, PyPI, etc. are from third parties and not from Microsoft, the node foundation, the Python Software Foundation, etc.Apple
@Apple Most, but by no means all. There are many official packages.Livialivid
D
39

If you don't want to always see the confirmation prompt, use the following:

Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('d:\foo.txt','OnlyErrorDialogs','SendToRecycleBin')

(solution courtesy of Shay Levy)

Depredation answered 14/1, 2014 at 16:25 Comment(1)
+1 for avoiding the prompt! Btw, keep mind that there is also DeleteDirectoryNimocks
S
22

It works in PowerShell pretty much the same way as Chris Ballance's solution in JScript:

 $shell = new-object -comobject "Shell.Application"
 $folder = $shell.Namespace("<path to file>")
 $item = $folder.ParseName("<name of file>")
 $item.InvokeVerb("delete")
Speckle answered 2/2, 2009 at 2:22 Comment(2)
There is a small bug in your answer (but it did work!). You need a quote before "path to file" $folder = $shell.Namespace(<path to file>") becomes $folder = $shell.Namespace("<path to file>")Debase
quotes only needed if you have blank space in pathsUltimatum
D
19

Here is a shorter version that reduces a bit of work

$path = "<path to file>"
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete")
Debase answered 2/2, 2009 at 16:14 Comment(1)
This asks with confirmation window.Importunity
B
11

Here's an improved function that supports directories as well as files as input:

Add-Type -AssemblyName Microsoft.VisualBasic

function Remove-Item-ToRecycleBin($Path) {
    $item = Get-Item -Path $Path -ErrorAction SilentlyContinue
    if ($item -eq $null)
    {
        Write-Error("'{0}' not found" -f $Path)
    }
    else
    {
        $fullpath=$item.FullName
        Write-Verbose ("Moving '{0}' to the Recycle Bin" -f $fullpath)
        if (Test-Path -Path $fullpath -PathType Container)
        {
            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
        }
        else
        {
            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
        }
    }
}
Byssinosis answered 29/11, 2015 at 10:15 Comment(0)
O
6

Remove file to RecycleBin:

Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('e:\test\test.txt','OnlyErrorDialogs','SendToRecycleBin')

Remove folder to RecycleBin:

Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::Deletedirectory('e:\test\testfolder','OnlyErrorDialogs','SendToRecycleBin')
Oversexed answered 17/1, 2017 at 13:57 Comment(0)
R
1

Here's slight mod to sba923s' great answer.

I've changed a few things like the parameter passing and added a -WhatIf to test the deletion for the file or directory.

function Remove-ItemToRecycleBin {

  Param
  (
    [Parameter(Mandatory = $true, HelpMessage = 'Directory path of file path for deletion.')]
    [String]$LiteralPath,
    [Parameter(Mandatory = $false, HelpMessage = 'Switch for allowing the user to test the deletion first.')]
    [Switch]$WhatIf
    )

  Add-Type -AssemblyName Microsoft.VisualBasic
  $item = Get-Item -LiteralPath $LiteralPath -ErrorAction SilentlyContinue

  if ($item -eq $null) {
    Write-Error("'{0}' not found" -f $LiteralPath)
  }
  else {
    $fullpath = $item.FullName

    if (Test-Path -LiteralPath $fullpath -PathType Container) {
      if (!$WhatIf) {
        Write-Verbose ("Moving '{0}' folder to the Recycle Bin" -f $fullpath)
        [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
      }
      else {
        Write-Host "Testing deletion of folder: $fullpath"
      }
    }
    else {
      if (!$WhatIf) {
        Write-Verbose ("Moving '{0}' file to the Recycle Bin" -f $fullpath)
        [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
      }
      else {
        Write-Host "Testing deletion of file: $fullpath"
      }
    }
  }

}

$tempFile = [Environment]::GetFolderPath("Desktop") + "\deletion test.txt"
"stuff" | Out-File -FilePath $tempFile

$fileToDelete = $tempFile

Start-Sleep -Seconds 2 # Just here for you to see the file getting created before deletion.

# Tests the deletion of the folder or directory.
Remove-ItemToRecycleBin -WhatIf -LiteralPath $fileToDelete
# PS> Testing deletion of file: C:\Users\username\Desktop\deletion test.txt

# Actually deletes the file or directory.
# Remove-ItemToRecycleBin -LiteralPath $fileToDelete

Rosemarie answered 25/6, 2021 at 21:15 Comment(0)
O
0

Here is a complete solution that can be added to your user profile to make 'rm' send files to the Recycle Bin. In my limited testing, it handles relative paths better than the previous solutions.

Add-Type -AssemblyName Microsoft.VisualBasic

function Remove-Item-toRecycle($item) {
    Get-Item -Path $item | %{ $fullpath = $_.FullName}
    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}

Set-Alias rm Remove-Item-toRecycle -Option AllScope
Odell answered 15/10, 2015 at 6:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.