Custom Parameters in Powershell. My god, I wish I’d started using these earlier than I did! It would have saved me SO much time, effort and, as it turns out, literally thousands of lines of code!
When I started my current job, one of the first thing I wanted to improve was the New Starter process. It was being done completely manually and was taking a serious amount of time for one of my colleagues. I figured that the best of of improving this situation was to put together a proper New Starter script. Now, this was 2/3 years ago, and my Powersehll skills were not what they are now. At the time i thought the best idea was to write a big script, with constant user prompts asking yes or no questions. This ended up taking me a good 3 months, and in the end was way over 2500 lines. To be fair, there was nothing wrong with this approach, it got the job done. That being said, it did have it’s problems. Updating it when things changed was a nightmare due to all the hard-coded elements, it was longer than it needed to be, and it was clunky.
Fast forward a couple of years, and I discover Powershell Functions (along with SWITCH statements, but that will be covered in a later post!). To say that this blew my mind is an understatement. This gave me a way to eliminate user questions (like “What is the persons name?”, “What is their department?”, “What is their job title?” etc etc.) and simply start using a purpose built cmdlet of my own!
Anyway, on to using parameters. This is all it took me, to get my script to use my own set of 6 parameters :
param( [Parameter(Mandatory=$True,Position=0)] [ValidateNotNull()] [string]$Name, [Parameter(Mandatory=$True,Position=1)] [string]$Title, [Parameter(Mandatory=$True, Position=2)] [string]$Department, [Parameter(Position=3)] [switch]$Fee, [Parameter(Position=4)] [string]$Initials, [Parameter(Position=5)] [int]$Ticket )
As you can see, it’s fairly self explanatory. I have 6 parameters, 3 of which are mandatory (ie script will error if they are not filled in) and 3 that are optional. That was it. That’s all that I needed to do. yes, there are more things that you can do with parameters, but as a starting point, that was all it needed. Six parameters, their types set to string, switch of integer, and some marked as mandatory.
If anyone has not ventured into using parameters yet, i strongly advise it. It literally revolutionised my Powershell coding!
…..god damn it, I wish I had learned this years ago!