如何使用PowerShell将文件移动到回收站?
默认情况下,当您使用PowerShell删除文件时,它将被永久删除。如何使用PowerShell将文件移动到回收站?
我想实际上已删除的项目转到回收站,就像我会通过shell删除发生。
如何在PowerShell中对文件对象执行此操作?
这里是一个较短的版本,减少一点工作
$path = "<path to file>"
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete")
它工作在PowerShell中相当多的方式克里斯·巴兰斯在JScript中的解决方案相同:
$shell = new-object -comobject "Shell.Application"
$folder = $shell.Namespace("<path to file>")
$item = $folder.ParseName("<name of file>")
$item.InvokeVerb("delete")
你的答案有一个小错误(但它确实有效!)。 你需要一个引号之前 “文件路径” $文件夹= $ shell.Namespace(“) 成为 $文件夹= $壳。名称空间(“”) – 2009-02-02 16:06:07
仅当路径中有空格时才需要引号 – RayofCommand 2013-12-05 09:49:37
的。如果你不这样做希望总是看到确认提示,请使用以下:
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('d:\foo.txt','OnlyErrorDialogs','SendToRecycleBin')
(谢伊的解决方案提供者Levy)
+1用于避免提示!顺便说一句,请记住,也有`DeleteDirectory` – marsze 2014-10-27 07:10:49
下面是一个完整的解决方案,可以添加到您的用户配置文件,使'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
下面是支持目录和文件作为输入的改进功能:
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')
}
}
}
删除文件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' )
2017年的答案:使用Recycle module
Install-Module -Name Recycle
然后运行:
Remove-ItemSafely file
我想为此制作一个名为trash
的别名。
一旦你选择了一个解决方案,你可以通过`Set-Alias rm Remove-ItemSafely -Option AllScope`来更新`rm`别名。 – bdukes 2015-07-31 15:46:05