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

I am trying to get manifest information for a custom PowerShell module in which the manifest file is stored along with the module file (psm1) in my directory structure.

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

+6
source share
2 answers

The psd1 file is a valid PowerShell script, so it’s best to allow PowerShell to parse the file.

The easiest way is to use the Test-ModuleManifest cmdlet. From C #, it looks something like this:

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 PowerShell parsing, for example. it would be easy to handle comments incorrectly or here lines when trying to use a regular expression.

+6
source

Add a link to System.Management.Automation . Then use the following code to get the Hashtable from the .psd1 file.

 static void Main(string[] args) { PowerShell ps = PowerShell.Create(); string psd = "C:\\Users\\Trevor\\Documents\\WindowsPowerShell\\Modules\\ISESteroids\\ISESteroids.psd1"; ps.AddScript(String.Format("Invoke-Expression -Command (Get-Content -Path \"{0}\" -Raw)", psd)); var result = ps.Invoke(); Debug.WriteLine(((Hashtable)result[0].ImmediateBaseObject)["Description"]); } 
0
source

Source: https://habr.com/ru/post/969549/


All Articles