問題描述
如何在 Windows 批處理腳本或 Perl 中將文件移動到回收站? (How can I move files to the Recycle Bin in a Windows batch script or Perl?)
I've got a Windows XP batch script which cleans some directories, but I would like to move the deleted files to trash instead of using plain del
. How is this done?
It looks like the only languages I can use for this is plain batch or Perl.
參考解法
方法 1:
use Win32::FileOp qw(Recycle);
Recycle(@ARGV);
方法 2:
Write a VBS script (Original Link) then call it with MyDelScript.vbs
function main()
{
if (WScript.Arguments.length != 1)
{
WScript.Echo("<Insert informative error message here>");
return;
}
var Path = WScript.Arguments(0);
var Shell = WScript.CreateObject("Shell.Application");
var Item = Shell.Namespace(0).ParseName(Path);
Item.InvokeVerb("delete");
}
方法 3:
The Win32::FileOp module has a Recycle
function. From the docs:
Recycle @filenames
Send the files into the recycle bin. You will not get any confirmation dialogs. Returns true if successful.
方法 4:
It can be done like this with plain batch and embedded VBScript. Put the following code into a file called recycle.cmd
:
<!-- : Begin batch script
@echo off
if "%1"=="" (
echo Usage: %~nx0 FILE_TO_RECYCLE[...]
echo This script puts files into the recycle bin
exit /b 1
)
cscript //nologo "%~f0?.wsf" %*
exit /b %errorlevel%
----- Begin embedded wsf script --->
<job><script language="VBScript">
Set app = WScript.CreateObject("Shell.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
For Each arg In WScript.Arguments
If fso.FileExists(arg) Then
Set file = fso.GetFile(arg)
Set folderItem = app.Namespace(0).ParseName(file.Path)
folderItem.InvokeVerb("delete")
Else
WScript.Echo "File not found: " & arg
End If
Next
</script></job>
Example:
echo This file is dirt.> dirt.txt
echo This file is trash.> trash.txt
recycle dirt.txt trash.txt
As you can see the script allows recycling multiple files with one command. It does not suppport the wildcards * and ? though.
The idea of embedding VBScript inside a batch file is taken from dbenham's answer to Is it possible to embed and execute VBScript within a batch file without using a temporary file? (scroll down to UPDATE 2014-04-27).
方法 5:
You could use the "recycle" utility which is part of CmdUtils from MaDdoG Software. From the page listing -
- Recycle, a safe replacement for the DEL command, that sends files to the recycle bin instead of deleting them. Recycle is also more flexible than DEL; you can specify multiple files at once (or use wildcards), and you can recycle whole directories at once (be careful!)
I would suggest you try its various switches before you incorporate it into your script - there is quite a bit of deviation from the default behaviour of the "del" command.
(by l0b0、FMc、Shay Erlichmen、Chas. Owens、giraffe、aks)