Skip to content

Instantly share code, notes, and snippets.

@ducke
Forked from altrive/PowerShellv4_DynamicKeyword.md
Created September 24, 2018 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducke/f79a7a7557d018090d51206b75956c23 to your computer and use it in GitHub Desktop.
Save ducke/f79a7a7557d018090d51206b75956c23 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"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment