Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I avoid the 'dir' alias in Powershell scripts?

The powershell guidelines suggest avoiding the use of aliases in scripts, e.g. spelling out Get-Content instead of using gc, and using Foreach-Object instead of %.

For the most part I think this is good advice, but I'm having a hard time following it with the dir alias, at least when used with the filesystem (vs. the registry or such). It seems to me that dir is as good as or better than Get-ChildItem, in terms of readability. It's also not nearly as cryptic as something like gc (Get-Content) or lp (Out-Printer), although maybe someone with no background in cmd.exe scripting might disagree.

Anybody have an opinion on this? Should I keep using dir, or try to be more 'correct'?

like image 580
Charlie Avatar asked Sep 05 '25 03:09

Charlie


2 Answers

Aliases are fine for typing. But in a script, spell it out. What do you lose?

like image 85
John Saunders Avatar answered Sep 09 '25 00:09

John Saunders


I personally avoid aliases in scripts, but I use them at the command line. Two exceptions I have are ? for Where-Object and % for ForEach-Object. I use those all the time. But its just my personal convention. So there's no legitimate reason why other built-in aliases wouldn't also be fine to use.

But you should definitely avoid using non-standard aliases. Doug Finke made a function for PowerShell ISE that expands your aliases into their true names.

http://dougfinke.com/blog/index.php/2009/01/03/expand-alias-for-powershell-integrated-scripting-environment/

And I created a this script for PowerShell ISE that shows what non-standard commands your script relies on. It also takes aliases into account.

http://einsteintech.spaces.live.com/blog/cns!89E05724AF67A39E!840.entry

like image 34
Josh Avatar answered Sep 09 '25 02:09

Josh