Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read powershell manifest file (.psd1) using c#

Tags:

c#

powershell

I am trying to access manifest details for a custom PowerShell module that has the manifest file stored along with the module(psm1) file in my directory structure.

What is the best way to access the manifest details like Description, GUID etc?

like image 937
Vijay Avatar asked May 19 '14 20:05

Vijay


People also ask

What is a .psd1 file?

A module manifest is a PowerShell data file ( . psd1 ) that describes the contents of a module and determines how a module is processed. The manifest file is a text file that contains a hash table of keys and values.

How do I Unimport a PowerShell module?

-ModuleInfoSpecifies the module objects to remove. Enter a variable that contains a module object (PSModuleInfo) or a command that gets a module object, such as a Get-Module command. You can also pipe module objects to Remove-Module .

What is psd1 and psm1?

. psm1 files contain main source code for a powershell module and . psd1 manifest data. You have to install them.

How do I create a psd1 file?

The New-ModuleManifest cmdlet creates a new module manifest ( . psd1 ) file, populates its values, and saves the manifest file in the specified path. Module authors can use this cmdlet to create a manifest for their module.


1 Answers

A psd1 file is a valid PowerShell script, so it's best to let PowerShell parse the file.

The simplest way is to use the Test-ModuleManifest cmdlet. From C#, that would look something like:

using (var ps = PowerShell.Create())
{
    ps.AddCommand("Test-ModuleManifest").AddParameter("Path", manifestPath);
    var result = ps.Invoke();
    PSModuleInfo moduleInfo = result[0].BaseObject as PSModuleInfo;

    // now you can look at the properties like Guid or Description
}

Other approaches cannot handle the complexities of parsing PowerShell, e.g. it would be easy to incorrectly handle comments or here strings when trying to use a regex.

like image 160
Jason Shirk Avatar answered Oct 24 '22 14:10

Jason Shirk