Invoking Different Code Based on Parameter Value

by Nov 13, 2015

Here is a simple concept using an action parameter with a number of choices. Each choice refers to a script block that would be executed then.

#requires -Version 2
function Invoke-SomeAction
{
  param
  (
    [String]
    [Parameter(Mandatory=$true)]
    [ValidateSet('Deploy','Delete','Refresh')]
    $Action
  )
  
  $codeAction = @{}
  $codeAction.Deploy = { 'Doing the Deployment' }
  $codeAction.Delete = { 'Doing the Deletion' }
  $codeAction.Refresh = { 'Doing the Refresh' }

  & $codeAction.$Action

}

When you type Invoke-SomeAction after you ran the code, ISE would provide IntelliSense for the supported "Deployment", "Deletion", and "Refresh" actions. The simple PowerShell console would at least provide tab-completion for the action argument.

Depending on your choice, the appropriate script block would execute. As you see, the action script blocks can hold any code, even multi-page.

Twitter This Tip! ReTweet this Tip!