Should you avoid "dir" aliases in Powershell scripts?
The powershell guides suggest avoiding the use of aliases in scripts eg. Get-Content
instead gc
and using Foreach-Object
instead %
.
For the most part, I think this is good advice, but I have a hard time following it with an alias dir
, at least when used with a filesystem (versus a registry or such). It seems to me that it is dir
no worse than Get-ChildItem
, in terms of readability. It is also not nearly as cryptic as something like gc
( Get-Content
) or lp
( Out-Printer
), although perhaps someone with no background in cmd.exe scripts might disagree.
Anyone have an opinion on this? Should I be using dir
or trying to be more "correct"?
a source to share
I personally avoid aliases in scripts, but I use them on the command line. Are there two exceptions I have? for Where-Object and% for ForEach object. I use them all the time. But this is my personal convention. As such, there is no legitimate reason why other built-in aliases are not suitable for use either.
But you should definitely avoid using non-standard aliases. Doug Finke made a function for PowerShell ISE that expands your aliases to their real names.
And I created this script for PowerShell ISE that shows what non-standard commands your script uses. It also takes aliases into account.
http://einsteintech.spaces.live.com/blog/cns!89E05724AF67A39E!840.entry
a source to share
The philosophy behind PowerShell is to use whatever is convenient for you on the command line. This is why you have "ls" and "dir" as aliases for Get-ChildItem. However, when writing scripts, one-liners or any other that will be shared by others, always use fully qualified command names and all argument names to avoid confusion. In particular, never use custom aliases in scripts, as they break script outside of your environment.
a source to share