views:

138

answers:

4

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'?

+5  A: 

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

John Saunders
Well put. I'm going to accept this answer on the grounds that I can't provide any good answer to "what do you lose?". Which is to say, I don't really have much of a case for using 'dir', and I eventually decided to use Get-ChildItem after all.
Charlie
+5  A: 

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

Josh Einstein
I try not to use aliases in scripts with a few exceptions. If I'm doing a get-childitem against a filesystem provider, I use DIR because it seems more readable. I also sometimes use gwmi instead of get-wmiobject because it's so much shorter (and gwmi lines are usually long anyway).
Mike Shepard
+3  A: 

The PowerShell philosophy is to use whatever you're comfortable with at the command prompt. That's why you have both 'ls' and 'dir' as aliases for Get-ChildItem. However, when writing scripts, one-liners or anything that will be shared with others, always use the full command names and the full argument names to avoid confusion. In particular, never use custom aliases in scripts since they will break the script outside your environment.

kimsnarf
Good summarization of the guidelines, thanks.
Charlie
A: 

I don't see why... I've never avoided "ls" :)

slipsec