Title: Misuse of `SHEmptyRecycleBin` in `Clear-RecycleBin` cmdlet · Issue #6743 · PowerShell/PowerShell · GitHub
Open Graph Title: Misuse of `SHEmptyRecycleBin` in `Clear-RecycleBin` cmdlet · Issue #6743 · PowerShell/PowerShell
X Title: Misuse of `SHEmptyRecycleBin` in `Clear-RecycleBin` cmdlet · Issue #6743 · PowerShell/PowerShell
Description: Overview Clear-RecycleBin produces spurious error records when used in Windows PowerShell. (Yes I know this repo is dedicated to PowerShell Core, but since it contains the code, and UserVoice isn't quite effective, I'll just put the anal...
Open Graph Description: Overview Clear-RecycleBin produces spurious error records when used in Windows PowerShell. (Yes I know this repo is dedicated to PowerShell Core, but since it contains the code, and UserVoice isn't...
X Description: Overview Clear-RecycleBin produces spurious error records when used in Windows PowerShell. (Yes I know this repo is dedicated to PowerShell Core, but since it contains the code, and UserVoice isn...
Opengraph URL: https://github.com/PowerShell/PowerShell/issues/6743
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Misuse of `SHEmptyRecycleBin` in `Clear-RecycleBin` cmdlet","articleBody":"## Overview\r\n\r\n`Clear-RecycleBin` produces spurious error records when used in Windows PowerShell. (Yes I know this repo is dedicated to PowerShell Core, but since it contains the code, and UserVoice isn't quite effective, I'll just put the analysis here.)\r\n\r\nIn a freshly launched PowerShell instance, running `Clear-RecycleBin -Force` will produce the following error (whether or not the recycle bin is empty does not matter at all):\r\n\r\n```text\r\nClear-RecycleBin : The system cannot find the path specified\r\nAt line:1 char:1\r\n+ Clear-RecycleBin -Force\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~\r\n + CategoryInfo : InvalidOperation: (RecycleBin:String) [Clear-RecycleBin], Win32Exception\r\n + FullyQualifiedErrorId : FailedToClearRecycleBin,Microsoft.PowerShell.Commands.ClearRecycleBinCommand\r\n```\r\n\r\nHowever, subsequent invocations to the same command (with `-Force`) will not produce such error. Moreover, in a newly launched PowerShell instance, running `Clear-RecycleBin` (without `-Force`) and manually confirming the operation) will not write error.\r\n\r\n## Root Cause\r\n\r\nUpon close investigation, the root cause starts on [line 226](https://github.com/PowerShell/PowerShell/blob/ffa7e4bac0b2546c5a61fad7cd87ae353e3264dc/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs#L226) of `ClearRecycleBinCommand.cs`. Relevant excerpt:\r\n\r\n```csharp\r\nuint result = NativeMethod.SHEmptyRecycleBin(IntPtr.Zero, drivePath,\r\n NativeMethod.RecycleFlags.SHERB_NOCONFIRMATION |\r\n NativeMethod.RecycleFlags.SHERB_NOPROGRESSUI |\r\n NativeMethod.RecycleFlags.SHERB_NOSOUND);\r\n\r\nint lastError = Marshal.GetLastWin32Error();\r\nprogress.PercentComplete = 100;\r\nprogress.RecordType = ProgressRecordType.Completed;\r\nWriteProgress(progress);\r\n// 0 is for a successful operation\r\n// 203 comes up when trying to empty an already emptied recyclebin\r\n// 18 comes up when there are no more files in the given recyclebin\r\nif (!(lastError == 0 || lastError == 203 || lastError == 18))\r\n{\r\n Win32Exception exception = new Win32Exception(lastError);\r\n WriteError(new ErrorRecord(exception, \"FailedToClearRecycleBin\", ErrorCategory.InvalidOperation, \"RecycleBin\"));\r\n}\r\n```\r\n\r\nThe mistake here is to use `GetLastWin32Error` -- according to [`SHEmptyRecycleBin` function (Windows)](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762160.aspx) on MSDN, the function uses `HRESULT` to indicate error status. The documentation does not mention `GetLastError`, and it is true that the function does **not** call `SetLastError` on the caller thread before returning.\r\n\r\nThe fact that `GetLastError` returns 3 on the first invocation of `Clear-RecycleBin -Force` is purely accidental.\r\n\r\nPlaying around with `SHEmptyRecycleBin` indicates that it returns `S_OK` (`0`) for success (also documented), and `E_UNEXPECTED` (`0x8000FFFF`, catastrophic/unexpected failure) when the recycle bin is already empty. At this time, I would suggest remove error detection in the cmdlet, since `SHEmptyRecycleBin` doesn't know how to handle the case when the recycle bin is already empty at all -- we can't expect it to do any reasonable failure indication.\r\n\r\nThere could have been a time when `SHEmptyRecycleBin` uses `SetLastError` to indicate failure, and the code could have been written when the documentation wasn't updated.\r\n\r\n---\r\n\r\nI wrote a blog entry on this issue, and I found that the code is wrong in every way. If you're interested, read https://geelaw.blog/entries/clear-recyclebin-shemptyrecyclebin/\r\n\r\nMistakes made summarised into a list:\r\n\r\n- not declaring `[DllImport(SetLastError = true)]` and using `Marshal.GetLastWin32Error` to retrieve the possible error code set by `SHEmptyRecycleBin`, which won't work and will get the leftover of previous marshalled calls.\r\n- documentation for `SHEmptyRecycleBin` doesn't indicate that it will call `SetLastError`, and recommends that one use the return value to determine error status.\r\n- `SHEmptyRecycleBin` doesn't expect to deal with already emptied recycle bin.\r\n\r\nI would recommend anyone using this cmdlet use `Clear-RecycleBin -ErrorAction SilentlyContinue` to prevent irrelevant `ErrorRecord`.\r\n","author":{"url":"https://github.com/GeeLaw","@type":"Person","name":"GeeLaw"},"datePublished":"2018-04-26T12:23:42Z","url":"https://github.com/PowerShell/PowerShell/issues/6743"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:5d6647e6-5022-2c2e-53e9-7e380c040882 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | EAE2:2F6606:25D177E:34D7BCE:6AFD49FB |
| html-safe-nonce | 63ea1b237a479b90cf4e9ac7a1eb59064036d8545071efde9a543bf68bf041c4 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFQUUyOjJGNjYwNjoyNUQxNzdFOjM0RDdCQ0U6NkFGRDQ5RkIiLCJ2aXNpdG9yX2lkIjoiMzYyMzcwNDAzMzAxNDY2MzY3NSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | e6f115054a95c7b5307d0c5f7c11ecd01019e8263cf23d4c52cd372c4fcc5151 |
| hovercard-subject-tag | issue:318005364 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/PowerShell/PowerShell/6743/issue_layout |
| twitter:image | https://opengraph.githubassets.com/de0fa2766a823eac5c619aa5377b69d07f943134decca7dcbabcbf461f4bfe7f/PowerShell/PowerShell/issues/6743 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/de0fa2766a823eac5c619aa5377b69d07f943134decca7dcbabcbf461f4bfe7f/PowerShell/PowerShell/issues/6743 |
| og:image:alt | Overview Clear-RecycleBin produces spurious error records when used in Windows PowerShell. (Yes I know this repo is dedicated to PowerShell Core, but since it contains the code, and UserVoice isn't... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | GeeLaw |
| hostname | github.com |
| expected-hostname | github.com |
| None | 66653c2e55a6fff2930be1bdf07ee4f8aa137e3956d056c822563be6f878755e |
| turbo-cache-control | no-preview |
| go-import | github.com/PowerShell/PowerShell git https://github.com/PowerShell/PowerShell.git |
| octolytics-dimension-user_id | 11524380 |
| octolytics-dimension-user_login | PowerShell |
| octolytics-dimension-repository_id | 49609581 |
| octolytics-dimension-repository_nwo | PowerShell/PowerShell |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 49609581 |
| octolytics-dimension-repository_network_root_nwo | PowerShell/PowerShell |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | b6f01f7cb9f35f8c09949773241a3d49dd04b340 |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width