PowerShell script parameter options

Is there an easy way to parse parameters from powershell script file

param( [string]$name, [string]$template ) 

I started reading the file and wondered if there is a better way, maybe using the help / man command?

 class PowerShellParameter { public string Name; public string Type; public string Default; } string[] lines = File.ReadAllLines(path); bool inparamblock = false; for (int i = 0; i < lines.Length; i++) { if (lines[i].Contains("param")) { inparamblock = true; } else if (inparamblock) { new PowerShellParameter(...) if (lines[i].Contains(")")) { break; } } } 
+4
source share
3 answers

There are at least two possibilities. First (better imho): use Get-Command :

 # my test file @' param( $p1, $p2 ) write-host $p1 $p2 '@ | Set-content -path $env:temp\sotest.ps1 (Get-Command $env:temp\sotest.ps1).parameters.keys 

For all participants look

 Get-Command $env:temp\sotest.ps1 | gm #or Get-Command $env:temp\sotest.ps1 | fl * 

Another (harder way) is to use regex

 [regex]::Matches((Get-Help $env:temp\sotest.ps1), '(?<=\[\[-)[\w]+') | select -exp Value 
+4
source

I like the solution with Get-Command proposed by @stej. Unfortunately, this does not work if the script parameters are of explicit types, and an assembly of this type is not yet loaded into the session. This is why I still use this script: Get script parameter names

+3
source

I'm not quite sure what you need is to document your scripts? In this case, see Get-Help about_Comment_Based_Help . It will tell you how to do this, and after that you can use Get-Help on your script / module.

If you are doing more rigorous parameter processing, take a look at about_functions_advanced_parameters and about_functions_cmdletbindings on how to best structure parameters. For instance,

[Parameter(Position=0,Mandatory=$true,HelpMessage='Enter architecture("OSX","WinXP","Win7","Linux")')] [ValidateSet("OSX","WinXP","Win7","Linux")] [string]$architecture

will make this parameter mandatory, read commands from position 0, allow only the value from the given set, and give a brief help message when prompting for input if this parameter was not specified.

+1
source

Source: https://habr.com/ru/post/1345183/


All Articles