Continuing on from me last article, now we are looking at why using an alias in your script is not a good idea.
There are a lot of aliases out there in PowerShell. Some even use the same alias as *nix commands (ls,ps) and also as the command.exe commands you are used to (mkdir,dir). While this is perfectly fine when working directly in the console running commands that do not require much effort or something that isn’t complicated.
Even if you have been using PowerShell for a while, odds are there are aliases that you haven’t seen and wouldn’t even know what cmdlet it maps to.
Take a look at this:
gps -id 3720 | % { $_.Name }
Unless you use this often, then you might not know that gps is actually Get-Process and the “%” (modulus) is actually the alias for “ForEach-Object”. All this does is make it more difficult to read the code that was written and creates more work for the person trying to understand what the code is actually doing.
Use this instead:
Get-Process -Id 3720 | ForEach { $_.Name }
While this example is not that impressive, imagine going through 100+ lines of code having to translate aliased cmdlets. Not much fun and it won’t help you score any more points in the Scripting Games either.
The same goes for parameters for each cmdlet. While it is tempting to shorten the parameter in an effort to save space, go ahead and expand the parameter out to what it should be. This will not only help you out if you have to go back to the script for some reason and also help others out who might be looking at your code to learn or troubleshoot.
Don’t do this:
Get-WmiObject -co dc1 -cl win32_service -f "name='wmi'"
Do this:
Get-WmiObject -Computer dc1 -Class win32_service -Filter "name='wmi'"
Makes the code look much cleaner and more easier to read.
Remember, use the full cmdlet name, no aliases at all in your script. Regardless of how cool it might look to use nothing but aliases. Same goes for the parameters for each cmdlet. Make it as readable as you can because not only could you be the one to come back to the code later on, but others might also be looking at your code and you want to have the best presentation possible!
Pingback: PowerShell script best practices | mnaoumov.NET