Skip to content

Instantly share code, notes, and snippets.

@SeeminglyScience
Last active January 12, 2024 11:00
Show Gist options
  • Save SeeminglyScience/533140625f67f2f46535e652c8cd6da2 to your computer and use it in GitHub Desktop.
Save SeeminglyScience/533140625f67f2f46535e652c8cd6da2 to your computer and use it in GitHub Desktop.
Cmdlet example using only PowerShell.
# https://seeminglyscience.github.io/powershell/2017/04/13/cmdlet-creation-with-powershell
using namespace System.Management.Automation
using namespace System.Reflection
[Cmdlet([VerbsDiagnostic]::Test, 'Cmdlet')]
class TestCmdletCommand : PSCmdlet {
[Parameter(ValueFromPipeline)]
[object]
$InputObject;
[void] ProcessRecord () {
$this.WriteObject($this.InputObject)
}
}
$cmdletEntry = [Runspaces.SessionStateCmdletEntry]::new(
<# name: #> 'Test-Cmdlet',
<# implementingType: #> [TestCmdletCommand],
<# helpFileName: #> $null
)
$internal = $ExecutionContext.SessionState.GetType().
GetProperty('Internal', [BindingFlags]'Instance, NonPublic').
GetValue($ExecutionContext.SessionState)
$internal.GetType().InvokeMember(
<# name: #> 'AddSessionStateEntry',
<# invokeAttr: #> [BindingFlags]'InvokeMethod, Instance, NonPublic',
<# binder: #> $null,
<# target: #> $internal,
<# args: #> @(
<# entry: #> $cmdletEntry
<# local: #> $true
)
)
Export-ModuleMember -Cmdlet Test-Cmdlet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment