Skip to content

Instantly share code, notes, and snippets.

@altrive
Last active August 3, 2023 02:28
Show Gist options
  • Save altrive/5864208 to your computer and use it in GitHub Desktop.
Save altrive/5864208 to your computer and use it in GitHub Desktop.
Test code of PowerShell v4 Dynamic Keyword

Define DynamicKeyword

Define DynamicKeyword 'ExecTest'

Note: Don't copy&paste from following code. PowerShell SyntaxHighlighter remove some lines. Instead, use RAW view.

#Requires -Version 4.0
Set-StrictMode -Version Latest

#Reset Existing Dynamic Keywords
[System.Management.Automation.Language.DynamicKeyword]::Reset()

#Add Dynamic Keyword
$keyword = New-Object System.Management.Automation.Language.DynamicKeyword
$keyword.Keyword ="ExecTest"
$keyword.BodyMode = [Management.Automation.Language.DynamicKeywordBodyMode]::HashTable
$keyword.NameMode =  [Management.Automation.Language.DynamicKeywordNameMode]::NoName
$prop = New-Object System.Management.Automation.Language.DynamicKeywordProperty
$prop.Name="ABC"
$prop.Mandatory = $true
$keyword.Properties.Add($prop.Name,$prop)
[System.Management.Automation.Language.DynamicKeyword]::AddKeyword($keyword)

#Define Function to process DynamicKeyword
function ExecTest{
param (
[Parameter(Mandatory)]
$KeywordData,
[string[]] $Name,
[Parameter(Mandatory)]
[hashtable] $Value,
[Parameter(Mandatory)]
$SourceMetadata
)
    $PSBoundParameters
}

Use DynamicKeyword

Use DynamicKeyword 'ExecTest' Note: Execute command separately,DynamicKeyword need to defined before use.

ExecTest{
    ABC = "abc"
}
@oising
Copy link

oising commented Jun 28, 2013

I don't think this works at all. It's just executing the function directly.

@altrive
Copy link
Author

altrive commented Jun 28, 2013

PowerShell SyntaxHighlighter remove some code lines from view. Please copy&paste from RAW view.

@ebekker
Copy link

ebekker commented Jan 19, 2016

Does anyone know if there is some way to "package" this up so that it can be used in a module and be recognized by ISE? In all of my testing, the only way this pattern of code works is if the DK setup code and associated function are inline with the code that uses it.

I'm trying to add a DSL-like extension to PS that would be detected by ISE and guide users similar to how DSC works -- but wasn't sure if this is actually a supported feature in ISE with the code above?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment