Last active
January 23, 2017 17:12
-
-
Save devblackops/edafff0109b42bd49f6638ffc7d3c3b1 to your computer and use it in GitHub Desktop.
Custom attributes attached to PowerShell function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type -TypeDefinition @" | |
namespace PoshBot { | |
public class BotCommand : System.Attribute { | |
public string Description { get; set; } | |
} | |
} | |
"@ | |
function Foo { | |
[PoshBot.BotCommand(Description = 'This is a custom function description')] | |
[cmdletbinding()] | |
param( | |
[PoshBot.BotCommand(Description = 'This is a custom parameter description')] | |
[parameter(mandatory)] | |
[string]$Name | |
) | |
Write-Output $Name | |
} | |
function Get-ParameterMetadata { | |
param ( | |
[parameter(mandatory)] | |
[System.Management.Automation.FunctionInfo]$Command, | |
[parameter(mandatory)] | |
[string]$ParameterName | |
) | |
$param = $Command.Parameters.$ParameterName | |
if ($param) { | |
$param.Attributes | Foreach-Object { | |
if ($_.TypeId.ToString() -eq 'PoshBot.BotCommand') { | |
$_ | |
} | |
} | |
} | |
} | |
function Get-CommandMetadata { | |
param ( | |
[parameter(mandatory)] | |
[System.Management.Automation.FunctionInfo]$Command | |
) | |
$attrs = $Command.ScriptBlock.Attributes | |
$attrs | ForEach-Object { | |
if ($_.TypeId.ToString() -eq 'PoshBot.BotCommand') { | |
$_ | |
} | |
} | |
} | |
$cmd = (Get-Command -Name Foo) | |
Get-CommandMetadata -Command $cmd | |
Get-ParameterMetadata -Command $cmd -ParameterName Name | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment