{"record":{"id":"551b54f67212a715","repo":"BornToBeRoot/NETworkManager","slug":"string-join-ps-streams-error-select-e-e-tostring","errorCode":null,"errorMessage":"string.Join(\"; \", ps.Streams.Error.Select(e => e.ToString()))","messagePattern":"string\\.Join\\(\"; \", ps\\.Streams\\.Error\\.Select\\(e => e\\.ToString\\(\\)\\)\\)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"Source/NETworkManager.Models/Network/NetworkInterface.cs","lineNumber":575,"sourceCode":"    /// Use <see langword=\"false\"/> for <c>netsh</c>, whose exit codes are unreliable\n    /// for idempotent operations (e.g. returns 1 when already on DHCP).\n    /// </summary>\n    private static void RunCommands(IEnumerable<string> commands, bool checkExitCode = false)\n    {\n        string script;\n\n        if (checkExitCode)\n            script = string.Join(Environment.NewLine, commands.Select(cmd =>\n                $\"{cmd}{Environment.NewLine}if ($LASTEXITCODE -ne 0) {{ Write-Error \\\"Command failed with exit code $LASTEXITCODE\\\" }}\"));\n        else\n            script = string.Join(Environment.NewLine, commands);\n\n        using var ps = SMA.PowerShell.Create();\n        ps.AddScript(script);\n        ps.Invoke();\n\n        if (checkExitCode && ps.HadErrors)\n            throw new Exception(string.Join(\"; \", ps.Streams.Error.Select(e => e.ToString())));\n    }\n\n    #endregion\n\n}","sourceCodeStart":557,"sourceCodeEnd":580,"githubUrl":"https://github.com/BornToBeRoot/NETworkManager/blob/2780d65469917a296dbc15f206107d72e2d0115c/Source/NETworkManager.Models/Network/NetworkInterface.cs#L557-L580","documentation":"RunCommands executes a PowerShell script built by callers (ConfigureNetworkInterface, FlushDns, ReleaseRenew, Add/RemoveIPAddressToNetworkInterface) and, when checkExitCode is set and ps.HadErrors is true, throws a generic Exception whose message is the ToString() of every error record joined with \"; \". The message therefore contains cmdlet-level errors (invalid parameters, missing elevation, cmdlet not found).","triggerScenarios":"Calling any wrapped network configuration operation while the generated script errors: renaming/configuring a NIC with invalid values (Enable-NetAdapter / Set-NetIPInterface / New-NetIPAddress failures), flushing DNS without rights, or ipconfig release/renew when no adapter matches.","commonSituations":"App not elevated (most NetAdapter/NetIPAddress cmdlets need admin); adapter name/alias changed or disconnected; conflicting static IP already assigned; media disconnected during release/renew.","solutions":["Run the application as administrator before changing network interface settings.","Refresh/validate the target interface name and state (connected, not renamed) before invoking the operation.","Catch the exception and display the joined error records, which identify the failing cmdlet and parameter.","Check ps.HadErrors/errors per command and fall back to querying Get-NetAdapter to diagnose."],"exampleFix":"// before\nawait NetworkInterface.FlushDns(); // throws with joined PS errors if not elevated\n// after\ntry\n{\n    await NetworkInterface.FlushDns();\n}\ncatch (Exception ex)\n{\n    Log.Warn($\"Flush DNS failed: {ex.Message}\");\n    MessageBox.Show(\"This operation requires administrator privileges.\");\n}","handlingStrategy":"try-catch","validationCode":"// pre-checks before network interface operations\nvar target = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()\n    .FirstOrDefault(n => n.Id == adapterId || n.Name == adapterName);\nbool isAdmin = new System.Security.Principal.WindowsPrincipal(\n    System.Security.Principal.WindowsIdentity.GetCurrent())\n    .IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);\nif (!isAdmin) throw new InvalidOperationException(\"Network configuration requires administrator privileges\");","typeGuard":"static bool IsElevated() => new System.Security.Principal.WindowsPrincipal(\n    System.Security.Principal.WindowsIdentity.GetCurrent())\n    .IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);","tryCatchPattern":"try\n{\n    await NetworkInterface.FlushDns();\n}\ncatch (Exception ex)\n{\n    // message contains each PS error record joined with \"; \"\n    foreach (var part in ex.Message.Split(\"; \"))\n        Log.Warn($\"PowerShell: {part}\");\n    throw new InvalidOperationException(\"Network operation failed (requires elevation?).\", ex);\n}","preventionTips":["Require elevation for all interface configuration operations.","Validate adapter name/id and connection state before invoking.","Log the joined error records; each names the failing cmdlet and parameter."],"tags":["powershell","network-interface","elevation","windows"],"backgroundTag":"api-error-response","analyzedSha":"2780d65469917a296dbc15f206107d72e2d0115c","analyzedAt":"2026-09-12T17:00:17.986Z","contentChangedAt":"2026-09-12T17:00:17.986Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}