Skip to content

Instantly share code, notes, and snippets.

@SimonWahlin
Created October 13, 2016 17:27
Show Gist options
  • Save SimonWahlin/275039888ab80c600b52f7d456134a2e to your computer and use it in GitHub Desktop.
Save SimonWahlin/275039888ab80c600b52f7d456134a2e to your computer and use it in GitHub Desktop.
Example of dynamic parameters with PowerShell
function Test {
[cmdletbinding()]
param(
[Parameter(Mandatory=$true,Position=1)]
[string]$smtpServer,
[Parameter(Position=2)]
[switch]$logging,
[Parameter(Position=4)]
[switch]$testing
    )
DynamicParam {
if( $logging -or $testing) {
$paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
}
if ($logging) {
$logPathAttribute = New-Object System.Management.Automation.ParameterAttribute -Property @{
Position = 3
Mandatory = $true
HelpMessage = 'Plesae enter path to log.'
}
$attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($logPathAttribute)
$logPathParam = New-Object System.Management.Automation.RuntimeDefinedParameter('LogPath', [String], $attributeCollection)
$paramDictionary.Add('LogPath', $logPathParam)
}
if ($testing) {
$testRecipientAttribute = New-Object System.Management.Automation.ParameterAttribute -Property @{
Position = 5
Mandatory = $true
HelpMessage = 'Plesae enter recipent.'
}
$attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($testRecipientAttribute)
$testRecipientParam = New-Object System.Management.Automation.RuntimeDefinedParameter('TestRecipient', [String], $attributeCollection)
$paramDictionary.Add('TestRecipient', $testRecipientParam)
}
if($logging -or $testing) {
return $paramDictionary
}
}
Process {
# Actual code goes here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment