代码之家  ›  专栏  ›  技术社区  ›  Omar Shahine

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

  •  37
  • Omar Shahine  · 技术社区  · 17 年前

    默认情况下,使用PowerShell删除文件时,文件将被永久删除。

    我真的想让删除的项目去回收站,就像我会发生通过外壳删除。

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

    7 回复  |  直到 8 年前
        1
  •  27
  •   John Pankowicz    12 年前

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

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

    (由Shay Levy提供解决方案)

        2
  •  18
  •   Scott Saad    17 年前

    它在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")
    
        3
  •  16
  •   Omar Shahine    17 年前

    这里有一个较短的版本,可以减少一点工作量

    $path = "<path to file>"
    $shell = new-object -comobject "Shell.Application"
    $item = $shell.Namespace(0).ParseName("$path")
    $item.InvokeVerb("delete")
    
        4
  •  11
  •   mikemaccana    8 年前

    2017答 使用 Recycle module

    Install-Module -Name Recycle
    

    然后运行:

    Remove-ItemSafely file
    

    我喜欢化名 trash 为此。

        5
  •  9
  •   sba923    10 年前

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

    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')
            }
        }
    }
    
        6
  •  2
  •   Mario Cianciolo    8 年前

    删除要回收的文件bin:

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

    删除要回收的文件夹bin:

    Add-Type -AssemblyName Microsoft.VisualBasic
    [Microsoft.VisualBasic.FileIO.FileSystem]::Deletedirectory('e:\test\testfolder','OnlyErrorDialogs','SendToRecycleBin')
    
        7
  •  0
  •   Mark S.    11 年前

    这里有一个完整的解决方案,可以添加到您的用户配置文件中,使“rm”将文件发送到回收站。在我有限的测试中,它比以前的解决方案更好地处理相对路径。

    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
    
    推荐文章