{"record":{"id":"3e4724d44d6e3584","repo":"itsfatduck/optimizerDuck","slug":"revert-usbpower-error-commandfailed-stderr-if-present-else","errorCode":null,"errorMessage":"Revert.UsbPower.Error.CommandFailed (stderr if present, else localized message with exit code)","messagePattern":"Revert\\.UsbPower\\.Error\\.CommandFailed \\(stderr if present, else localized message with exit code\\)","errorType":"exception","errorClass":"StepExecutionException","httpStatus":null,"severity":"error","filePath":"optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs","lineNumber":74,"sourceCode":"            \"$json = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('\"\n            + payload\n            + \"')); \"\n            + \"$states = $json | ConvertFrom-Json; \"\n            + \"foreach ($s in $states) { \"\n            + \"$obj = Get-CimInstance -Namespace root\\\\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue | \"\n            + \"Where-Object { $_.InstanceName -eq $s.InstanceName }; \"\n            + \"if ($obj -and $obj.Enable -ne [bool]$s.Enable) { \"\n            + \"Set-CimInstance -CimInstance $obj -Property @{ Enable = [bool]$s.Enable } | Out-Null \"\n            + \"}}\";\n\n        var result = await shell.QueryPowerShellAsync(script, logger).ConfigureAwait(false);\n\n        if (result.ExitCode != 0)\n        {\n            var error = !string.IsNullOrWhiteSpace(result.Stderr)\n                ? result.Stderr\n                : Loc.Instance[\"Revert.UsbPower.Error.CommandFailed\", result.ExitCode];\n            throw new StepExecutionException(error, result.Stderr);\n        }\n\n        return true;\n    }\n\n    /// <inheritdoc />\n    public JObject ToData()\n    {\n        return new JObject { [nameof(States)] = JArray.FromObject(States) };\n    }\n\n    /// <summary>\n    ///     Deserializes a <see cref=\"UsbPowerRevertStep\" /> from JSON data.\n    /// </summary>\n    public static UsbPowerRevertStep FromData(JObject data)\n    {\n        var states = data[nameof(States)]?.ToObject<List<DeviceState>>() ?? [];\n","sourceCodeStart":56,"sourceCodeEnd":92,"githubUrl":"https://github.com/itsfatduck/optimizerDuck/blob/36acf585ae122a09f0e29eb4acedfaf94e81c0de/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs#L56-L92","documentation":"UsbPowerRevertStep.ExecuteAsync throws StepExecutionException when the command that restores USB power settings (per-device DeviceState enable/disable) exits non-zero. Like the shell step, stderr wins over the localized 'Revert.UsbPower.Error.CommandFailed' message with the exit code, and stderr is stored as the detail.","triggerScenarios":"The PowerShell/CMD restoration command for USB selective suspend / device power settings failed: target device unplugged so its instance path is gone, driver reinstalled with a new instance name, or powercfg invocation blocked (rights or policy).","commonSituations":"USB device removed before revert; device instance renamed after driver update; power plan recreated so the stored settings reference is stale; running unelevated where powercfg changes require admin.","solutions":["Read the attached stderr for the specific failure and fix it (replug the device, install the driver).","Run the app as administrator — USB power configuration typically requires elevation.","Re-apply the USB power optimization to regenerate fresh revert data with current device instance paths, then revert.","If the device is permanently gone, delete the revert file for that optimization id."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"// device present check before reverting USB power state\nbool present = new ManagementObjectSearcher(\"SELECT InstanceName FROM Win32_USBHub\")\n    .Get().Cast<ManagementObject>().Any(m => instanceName.Contains(m[\"InstanceName\"].ToString()));","typeGuard":null,"tryCatchPattern":"try { await usbStep.ExecuteAsync(opCall); }\ncatch (StepExecutionException ex)\n{ logger.LogError(\"USB power revert failed: {Err}\", ex.Detail ?? ex.Message); }","preventionTips":["Keep the device connected during revert","Re-apply to refresh DeviceState after driver updates","Run elevated for powercfg changes","Treat stale instance paths as expected failures and regenerate revert data"],"tags":["csharp","usb","powercfg","powershell","revert"],"backgroundTag":"command-not-found","analyzedSha":"36acf585ae122a09f0e29eb4acedfaf94e81c0de","analyzedAt":"2026-09-13T08:30:13.845Z","contentChangedAt":"2026-09-13T08:30:13.845Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}