Skip to content

Instantly share code, notes, and snippets.

@chrisfcarroll
Last active July 29, 2025 10:09
Show Gist options
  • Save chrisfcarroll/d31b34dd0d7f5ca674f08cccb95044d8 to your computer and use it in GitHub Desktop.
Save chrisfcarroll/d31b34dd0d7f5ca674f08cccb95044d8 to your computer and use it in GitHub Desktop.
PowerShell example of getting parameter names from the script file with a regex for each parameter
#
# Get parameter values from the script file name.
#
$validparam1s= "Value1|Value2|Value3"
$param1PatternInFileName = "[^ \.]+(?=\.ps1$)"
$param1= (select-string -Pattern $param1PatternInFileName -InputObject $MyInvocation.MyCommand.Name).Matches.Value
if(-not( $param1 -match $validparam1s))
{
throw "$($MyInvocation.MyCommand.Name) does not end with a valid param1 name. Expected one of $validparam1s."
}
$validparam2s= 1,2
$param2PatternInFileName = "(?<=Step )(\d)(?=.+\.ps1$)"
$param2= (select-string -Pattern $param2PatternInFileName -InputObject $MyInvocation.MyCommand.Name).Matches.Value
if(-not( $validparam2s -contains $param2))
{
throw "$($MyInvocation.MyCommand.Name) does not name a valid param2. Expected 'Step 1 ' or 'Step 2 '"
}
#----------------------------------------------------------
$script= Join-Path (split-path -parent $MyInvocation.MyCommand.Definition) "Script.ps1"
& "$script" -param1 "$param1" -param2 $param2
#----------------------------------------------------------
# Or:
function actualFunction($p1, $p2){
# ...
}
actualFunction $param1 $param2
@chrisfcarroll
Copy link
Author

Originally written for deployment scripts, where the main parameter is an environment name

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