Skip to content

Instantly share code, notes, and snippets.

@rjmholt
Last active December 7, 2020 21:38
Show Gist options
  • Save rjmholt/e9d935e998d9fa9d450e22e49491f199 to your computer and use it in GitHub Desktop.
Save rjmholt/e9d935e998d9fa9d450e22e49491f199 to your computer and use it in GitHub Desktop.
Use a hidden/unexported binary cmdlet in C#
using System;
using System.Linq;
using System.Management.Automation;
// Notice no [Cmdlet] attribute, otherwise PowerShell will export this cmdlet
// However, if you use this with a manifest you can add the attribute and just omit it from the manifest
// (the DLL will export the cmdlet, but then its absence in the manifest will filter it out)
internal class HiddenCmdlet : Cmdlet
{
[Parameter]
public string Name { get; set; }
protected override void EndProcessing()
{
WriteObject($"Hello, {Name}");
}
}
internal class Program
{
internal static void Main(string[] args)
{
using (var pwsh = PowerShell.Create())
{
// Notice that you can give anything as the cmdlet name here.
// It has no true name since there's no attribute,
// and can never be invoked by name anyway (it's hidden).
// This string is just required by the API for things like transcription
string result = pwsh.AddCommand(new CmdletInfo(name: "Write-Hello", typeof(HiddenCmdlet)))
.AddParameter("Name", "Terrence")
.Invoke<string>()
.FirstOrDefault();
// Prints "Hello, Terrence"
Console.WriteLine(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment