如何使用PowerShell将文件移动到回收站?

Oma*_*ine 38 powershell

默认情况下,当您使用PowerShell删除文件时,它将被永久删除.

我想将删除的项目实际上转到回收站,就像我通过shell删除一样.

如何在PowerShell中对文件对象执行此操作?

Joh*_*icz 27

如果您不想总是看到确认提示,请使用以下命令:

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

(解决方案由Shay Levy提供)

  • +1以避免提示!顺便说一下,请记住还有"DeleteDirectory" (5认同)

小智 18

它在PowerShell中的工作方式与Chris Ballance在JScript中的解决方案非常相似:

 $shell = new-object -comobject "Shell.Application"
 $folder = $shell.Namespace("<path to file>")
 $item = $folder.ParseName("<name of file>")
 $item.InvokeVerb("delete")
Run Code Online (Sandbox Code Playgroud)


Oma*_*ine 17

这是一个缩短版本,减少了一些工作

$path = "<path to file>"
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete")
Run Code Online (Sandbox Code Playgroud)

  • 这会询问确认窗口。 (2认同)

mik*_*ana 15

2017答案:使用回收模块

Install-Module -Name Recycle
Run Code Online (Sandbox Code Playgroud)

然后运行:

Remove-ItemSafely file
Run Code Online (Sandbox Code Playgroud)

我喜欢trash为这个做一个别名.


sba*_*sba 9

这是一个改进的函数,它支持目录和文件作为输入:

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')
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

将文件删除到回收站:

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

将文件夹删除到回收站:

Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::Deletedirectory('e:\test\testfolder','OnlyErrorDialogs','SendToRecycleBin')
Run Code Online (Sandbox Code Playgroud)