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

后端 未结 7 970
攒了一身酷
攒了一身酷 2020-12-07 20:19

By default when you delete a file using PowerShell it\'s permanently deleted.

I would like to actually have the deleted item go to the recycle bin just like I would

相关标签:
7条回答
  • 2020-12-07 20:58

    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)

    0 讨论(0)
  • 2020-12-07 21:01

    2017 answer: use the Recycle module

    Install-Module -Name Recycle
    

    Then run:

    Remove-ItemSafely file
    

    I like to make an alias called trash for this.

    0 讨论(0)
  • 2020-12-07 21:02

    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")
    
    0 讨论(0)
  • 2020-12-07 21:10

    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")
    
    0 讨论(0)
  • 2020-12-07 21:13

    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')
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-07 21:15

    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')
    
    0 讨论(0)
提交回复
热议问题