Argyll
Argyll

Reputation: 9875

How to delete a folder with content to recycle bin in Matlab

I am running Matlab R2020b on Windows 10.

Is there a way to move a folder with content to recycle bin programmatically in Matlab?

For example, the following works for single files

previousState=recycle('on');
delete(filename); % if replaced with rmdir(DIR,'s');, folder is deleted permanently
recycle(previousState);

but the same toggle doesn't work for folders. Is there a way?


The only possible workaround I can think of is to use wildcard: delete(fullfile(DIR,'*') and then rmdir(DIR) on the empty folder. But that doesn't work for my application. I wish to preserve temporary copies of folders in recycle bin in case my script that manipulate them throws warning in some unexpected way, in which case I can have a second chance to see the original files. There are hundreds of folders, each contain hundreds to thousands of files in this particular use case. The wildcard approach does put individual files into recycle bin but it loses the original folder structure, making it impractical to selectively recover folders. Hence the question.

Upvotes: 1

Views: 540

Answers (1)

Argyll
Argyll

Reputation: 9875

Since the OS is specifically Windows 10, one can use powershell as shown here.

For example, with the following recycleFile.ps1 file in C:\

Param(
  [string]$filePath # can be folder
)

$sh = new-object -comobject "Shell.Application"
$ns = $sh.Namespace(0).ParseName($filePath)
$ns.InvokeVerb("delete")

the following passage in Matlab will move the folder fullfilepath to recycle bin,

[status,cmdout]=system(['powershell.exe -ExecutionPolicy Bypass -File "',...
                            fullfile('C:','recycleFile.ps1'),'" "',...
                            fullfilepath),'"']);

There are several downsides, however.

The operation is equivalent to context menu -> delete. It will bring up the recycle progress UI which seizes foreground. It is also somewhat slow. It may even require user confirmation if the folder in question is not eligible for recycling but only for direct deletion.

Upvotes: 1

Related Questions