Execute a PowerShell Script in C#: .NET 10 and sample fixes - #2264
Merged
vladimir-pecanac-main merged 3 commits intoOct 5, 2026
Conversation
- Both projects net7.0 to net10.0; Microsoft.PowerShell.SDK 7.3.3 to 7.6.6 (7.6.x targets net10.0 only); test packages bumped, xunit kept. - ProcessStart: start pwsh instead of powershell.exe, build arguments with ArgumentList, set UseShellExecute = false, read stdout and stderr asynchronously and wait for exit, return exit code, output and error. - PowerShellClass.ExecuteScript: AddCommand instead of AddScript (a path with a space fails under AddScript) and a Bypass execution policy through InitialSessionState, since a hosted runspace otherwise inherits Restricted. - ExecuteCommand: FirstOrDefault and a HadErrors check instead of First(). - PSCustomRunspace implements IDisposable and disposes its runspace. - echo.ps1 added to the project; no more hardcoded desktop path. - Program.cs uses top-level statements.
Drop the Microsoft.PowerShell.Utility import from PSCustomRunspace, which made every cmdlet in that module (Get-Random, Invoke-Expression and more) callable. The runspace now holds the Get-Date entry alone. Program.cs comment names gedit as the Linux example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Sample update for the article "Execute a PowerShell Script in C#" (https://code-maze.com/csharp-run-powershell-script/). Only dotnet-cli/ExecutingPowerShellScript changes.
Packages (re-queried on NuGet 2026-10-04):
dotnet list package --vulnerable --include-transitive: clean.
Changes:
Local run (Windows, SDK 10.0.302, runtime 10.0.10, pwsh 7.6.6): build 0 warnings 0 errors; 7 of 8 tests passed, the eighth (starts Notepad) not run locally. All test classes keep the Live suffix, so CI builds the folder and runs none of them, as before.