How to execute a PowerShell command in c#

Denis Sav 21 Reputation points
2022-10-18T14:20:52.943+00:00

Hello everyone.
I would like to run a PowerShell command in a c# ( NetFramework 4.0) application.
For example this is the PowerShell command for Add file exclusion in Windows Defender:

Add-MpPreference -ExclusionPath "<Full path of file>" -Force  

How do I run this command in c#. I am asking for your help. Thanks in advance.

Developer technologies | C#
Developer technologies | 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.
{count} votes

Answer accepted by question author
  1. Michael Taylor 61,116 Reputation points
    2022-10-18T14:28:21.143+00:00

    While you can call PS from C# you really need to ask yourself why. PS is a wrapper around .NET. That PS command you're running is just going to call into .NET (using C# most likely). It would be faster to just make the call directly in C#. For this particular set of functions the docs say they are actually just PS functions so you could go look at what the module does and just replicate that code in C#.

    But 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.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Castorix31 91,511 Reputation points
    2022-10-18T14:30:42.83+00:00
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.