Writing binary PowerShell cmdlet in c#

PowerShell

Create a library project in Visual Studio

Install with the NuGet package manager

* PowerShellStandard.Library
* XmlDoc2CmdletDoc

Create a new class and inherit from CmdLet

Decorate the class with the CmdLet attribute:



[Cmdlet(VerbsCommon.Get, "Something")]

Decorate parameters with the Parameter attribute:


[Parameter(Mandatory=true)]
public string Name { get; set; }

If the dll references other assemblies, you should ensure the referenced assemblies are loaded properly

Add a code to handle it


static BaseCmdlet()
{
	AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{

    string assemblyFileName = args.Name.Split(',').First().Trim() + ".dll";

    string assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

    string assemblyFile = Path.Combine(assemblyDir, assemblyFileName);

    if (!File.Exists(assemblyFile))
       return null;

	return Assembly.LoadFrom(assemblyFile);

}

To run the cmdlet, load the module first


Import-Module c:\path\to\module.dll

Post a Comment

Previous Post Next Post