Use PowerShell cmdlets in C#

Hinterleitner Andreas 0 Reputation points
2024-06-27T13:32:37.0866667+00:00

Is it possible to use the cmdlets of a specific PowerShell version in C#? PowerShell has its limits regarding OO programming, so I'd like to use C# more, and make use of the power of the PowerShell cmdlets from within C#. My requirement is to have access to Windows-exclusive cmdlets and modules (for example, to manage Hyper-V and Windows Server failover clusters); I want to use the cmdlets of the most actual PowerShell version available.

Is this possible? If so, what are the software requirements (SDKs, runtimes,...)?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,571 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,569 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,272 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 42,146 Reputation points Microsoft Vendor
    2024-06-27T14:57:44.9333333+00:00

    Hi @Hinterleitner Andreas , Welcome to Microsoft Q&A,

    As long as there are functions in the document, you can use C# to call PowerShell to implement them.

    If you want to call a PS script/command in C# then you need to set up the PS session and then invoke the command. You can see the needed code here.

    You can also refer to:https://github.com/karenpayneoregon/power-shell-process-cs/blob/master/ProcessingAndWaitSimple/Classes/PowerShellOperations.cs

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments