This function parses parameters of a script and returns parameter names. For example, I use it in my own TabExpansion procedure. It requires PowerShell 2.0.
function GetScriptParameter ( # Full script path. $Path, # Script code (if $Path is not defined). $Script, # Parameter wildcard pattern (to get a subset). $Pattern ) { if ($Path) { $Script = [System.IO.File]::ReadAllText($Path) } $mode = 0 $param = $true $tokens = @([System.Management.Automation.PSParser]::Tokenize($Script, [ref]$null)) for($i = 0; $i -lt $tokens.Count; ++$i) { $t = $tokens[$i] # skip [ whatever ] if (($t.Type -eq 'Operator') -and ($t.Content -eq '[')) { $level = 1 for(++$i; $i -lt $tokens.Count; ++$i) { $t = $tokens[$i] if ($t.Type -eq 'Operator') { if ($t.Content -eq '[') { ++$level } elseif($t.Content -eq ']') { --$level if ($level -le 0) { break } } } } continue } switch($t.Type) { 'NewLine' { break } 'Comment' { break } 'Command' { if ($mode -le 1) { return } break } 'Keyword' { if ($mode -eq 0) { if ($t.Content -eq 'param') { $mode = 1 break } } } 'GroupStart' { if ($mode) { ++$mode break } else { return } } 'GroupEnd' { --$mode if ($mode -lt 2) { return } } 'Variable' { if ($mode -eq 2 -and $param) { $param = $false if ((!$Pattern) -or ($t.Content -like $Pattern)) { $t.Content } break } } 'Operator' { if (($mode -eq 2) -and ($t.Content -eq ',')) { $param = $true } } } } }
#1 by Douglas on October 16, 2008 - 6:13 pm
Excellent. For the past couple days I have been wanting to write this.
Thanks.