Wouldn’t it be nice if parameters would suggest valid arguments for the user? Sometimes they do. When you type below command and press a SPACE after -LogName, PowerShell ISE and Visual Studio Code pop up an IntelliSense menu with all log files you can dump:
PS> Get-EventLog -LogName
If no automatic Intellisense pops up (i.e. in the PowerShell console), you can press TAB for auto completion, or CTRL+SPACE to manually force the IntelliSense choices to appear.
You can do the same with your own PowerShell functions, and there are a number of ways to do this. In our last part we looked at the “ValidateSet” attribute. Today, we examine a super-secret similar attribute called “ArgumentCompleter”.
With ValidateSet, you can define a set of values the user can choose from. No other values are allowed.
What if you’d like to suggest – let’s say – the most frequently used servers to the user, but also allow the user to specify completely different servers? This is when the “ArgumentCompleter” attribute comes into play. It defines a list of suggested values but does not limit the user to these:
function Get-Vendor { param( [Parameter(Mandatory)] [ArgumentCompleter({'Microsoft','Amazon','Google'})] [string] $Vendor ) "Chosen vendor: $Vendor" }
When you run this and the call Get-Vendor, from inside the interactive PowerShell console, you can now press TAB or CTRL+SPACE to auto-complete or open IntelliSense lists. Unfortunately, the attribute won’t automatically pop up the IntelliSense menu for you, and it may not work inside the editor pane of PowerShell editors.
Still, the “ArgumentCompleter” attribute can be of tremendous help, especially for advanced users that use commands and tab-completion often. By adding default choices to parameters, the user can quickly tab through these but can also submit any other argument.
You are a PowerShell Professional, passionate about improving your code and skills? You take security seriously and are always looking for the latest advice and guidance to make your code more secure and faster? You’d love to connect to the vibrant PowerShell community and get in touch with other PowerShell Professionals to share tricks and experience? Then PowerShell Conference EU 2020 might be just the right place for you: https://psconf.eu (June 2-5, 2020 in Hanover, Germany).
It’s a unique mixture of classic conference with three parallel tracks filled with fast-paced PowerShell presentations, and advanced learning class with live discussions, Q&A and plenty of networking.
Secure your seat while they last: https://psconf.eu/register.html. The speakers and agenda is available here: https://psconf.eu/schedule.