• Powershell

    Dynamic Parameters discoverability

    In my previous post About Dynamic Parameters I forgot to mention an important point about discoverability. When I come across a new script or module, usually the first thing I do is to check its syntax to get an idea of the kind of arguments it can accept, like this: This concise syntax tells me for example that all parameters in the first ParameterSet are optional (each parameter and its type is enclosed in square brackets), meaning I can simply run Get-AzResource on an Azure Subscription and get the list of all available Resources. The second ParameterSet on the other hand requires at least the ResourceId parameter since it is not enclosed in square brackets; the other parameters are optional though, so I may or may not use them. And so on. Get-Help too shows the script’s syntax, along with additional help details if available: Dynamic Parameters are special though: As you can see, FolderPath is displayed as an optional parameter (expected) but there is no sign of FileName which we know will be created at runtime. That is the core of the matter: FileName does not appear in the param declaration, therefore Powershell does not see this as a…

  • Powershell

    About Dynamic Parameters

    A fundamental best practice for any programming or scripting language is do not trust your input parameters, always validate data users (but also other pieces of automation) pass into your program. It is easy it imagine how things can go badly wrong when a user by mistake passes a string where you are expecting an integer, or an array in place of a boolean, not to mention the security implications (and potential disaster) of, for example, accepting and running things such as a sql command or other shell commands malicious users may try to use to exploit your system. In Powershell we can use Parameter Validation attributes to check the format or the type of an input parameter, or check for null or empty strings, or that the passed value falls within a certain range, or force the user to pass only a value selected from a restricted list. This last type is called ValildateSet and allows the script author to decide the list of values the user can chose from and have Powershell throws an error if this constraint is not respected. I used it often in my scripts and modules, this is how a very simple script looks like: [CmdletBinding()]param (…