Skip to content

Instantly share code, notes, and snippets.

@devblackops
Last active January 23, 2017 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devblackops/edafff0109b42bd49f6638ffc7d3c3b1 to your computer and use it in GitHub Desktop.
Save devblackops/edafff0109b42bd49f6638ffc7d3c3b1 to your computer and use it in GitHub Desktop.
Custom attributes attached to PowerShell function
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