2

Is it possible to check if a powershell module ist installed in C#?

I need a C# condition if a module is / or is not installed.

I know how to use powershell in C#, but how become a response from Powershell?

Thanks for reading my question and i hope anyone can give me some hints.

1 Answer 1

5

You can add a reference to System.Management.Automation and use the PowerShell to invoke Get-Module cmdlet to check if a specific module has been installed:

var exists = false;
using (PowerShell ps = PowerShell.Create())
{
    string moduleName = "something";
    ps.AddScript($"Get-Module -ListAvailable -Name {moduleName}");
    var result = ps.Invoke();
    exists = result.Count > 0;
}

Note: To add a reference to System.Management.Automation, you can install the NuGet package using Install-Package System.Management.Automation.dll Or if you want to see where the dll is located on your system, using powershell console, you can see [PSObject].Assembly.Location and pick it.

Sign up to request clarification or add additional context in comments.

8 Comments

In your answer is an issue. result.Count is an Property not a method ;-)
In fact I used the linq Count() extension method which is usable when you have using System.Linq;
result.Count is a Property not a method
Oh ha. Thanks! My misstake.
@Marcus you might want to accept this answer if it solved your problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.