2009-02-02 64 views
33

默認情況下,當您使用PowerShell刪除文件時,它將被永久刪除。如何使用PowerShell將文件移動到回收站?

我想實際上已刪除的項目轉到回收站,就像我會通過shell刪除發生。

如何在PowerShell中對文件對象執行此操作?

+1

一旦你選擇了一個解決方案,你可以通過`Set-Alias rm Remove-ItemSafely -Option AllScope`來更新`rm`別名。 – bdukes 2015-07-31 15:46:05

回答

13

這裏是一個較短的版本,減少一點工作

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

它工作在PowerShell中相當多的方式克里斯·巴蘭斯在JScript中的解決方案相同:

$shell = new-object -comobject "Shell.Application" 
$folder = $shell.Namespace("<path to file>") 
$item = $folder.ParseName("<name of file>") 
$item.InvokeVerb("delete") 
+0

你的答案有一個小錯誤(但它確實有效!)。 你需要一個引號之前 「文件路徑」 $文件夾= $ shell.Namespace(<文件路徑>「) 成爲 $文件夾= $殼。名稱空間(「<文件路徑>」) – 2009-02-02 16:06:07

+0

僅當路徑中有空格時才需要引號 – RayofCommand 2013-12-05 09:49:37

23

的。如果你不這樣做希望總是看到確認提示,請使用以下:

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

(謝伊的解決方案提供者Levy)

+3

+1用於避免提示!順便說一句,請記住,也有`DeleteDirectory` – marsze 2014-10-27 07:10:49

0

下面是一個完整的解決方案,可以添加到您的用戶配置文件,使'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 
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') 
     } 
    } 
} 
0

刪除文件RECYCLEBIN
添加型-AssemblyName Microsoft.VisualBasic程序[微軟。 VisualBasic.FileIO.FileSystem] :: DeleteFile('e:\ test \ test.txt','OnlyErrorDialogs','SendToRecycleBin')

刪除文件夾以RECYCLEBIN
添加型-AssemblyName Microsoft.VisualBasic程序[Microsoft.VisualBasic.FileIO.FileSystem] :: Deletedirectory( 'E:\測試\ testfolder', 'OnlyErrorDialogs', 'SendToRecycleBin' )

10

2017年的答案:使用Recycle module

Install-Module -Name Recycle 

然後運行:

Remove-ItemSafely file 

我想爲此製作一個名爲trash的別名。

相關問題