r/PowerShell • u/Mental_Patient_1862 • Jan 15 '21
Aliases suck
Posted this in a reply to a separate thread but posting here to maybe get more folks onboard.
I truly wish folks would stop using aliases when helping people with code. Many (most?) of the questions here (and other forums) are from posters that are new to Powershell. Aliases just add another layer of confusion. As for me, I don't use them because 99% of what I do with PoSh is with scripts and using aliases in scripts makes them much harder to read. So yeah, I have to look them up too.
It's awesome that more experienced coders are willing to share their skill, it just seems to me it'd be awesomer if they would go that tiny extra mile to write out ForEach-Object instead of %, or Where-Object instead of ?, etc.
</whinge>
38
u/aussier1 Jan 15 '21
As soon as you paste the aliases in to any decent IDE, it should warn you to use the original version of the command.
0
Jan 15 '21
[deleted]
16
u/Blindkitty38 Jan 15 '21
Vscode cares about alias formatting and that's what I appreciates about it.
7
4
u/MonkeyNin Jan 16 '21
try this config
"powershell.codeFormatting.useCorrectCasing": true, "powershell.codeFormatting.autoCorrectAliases": true, "[powershell]": { "editor.formatOnSave": true, "editor.formatOnPaste": false, // if autoIndent is set to 'full' it breaks indentation on 'move line up/down' "editor.autoIndent": "advanced", },2
9
u/lucidhominid Jan 15 '21
Huh, its funny I use VSCode for to write scripts for my Unity projects and even a bit of .NET that I use in some of my Powershell modules, but I never even thought to use it for writing the PowerShell itself. Just loaded up the module Im working on in VSCode aaaaand I think I'm stickin with it.
16
u/IMayHaveBrokenThings Jan 15 '21
... 99% of what I do with PoSh ...
Did you just use an alias for PowerShell in a rant about alias's? :)
I agree, alias's shouldn't be used in scripts or when explaining something to someone. They do come in handy for one off commands in a shell though.
57
u/psthreathunter Jan 15 '21
I would add that if you goal is to teach like helping someone on a forum post then it is important to write code out in the most verbose fashion so it is easier to read. This includes not only avoiding aliases but when practical pass arguments via named parameters instead of by position. i.e.
Set-ItemProperty -Path "C:\stuff.txt" -Name IsReadOnly -Value $TrueInstead of
Set-ItemProperty "C:\stuff.txt" IsReadOnly $TrueBTW, one alias that I ALWAYS see used is $_ this is actually an alias for $PSItem. I only bring that up because I have had students (I teach PS for a living) that have asked what is $PSItem when they see it not realizing they have been using it for days in class.
28
u/omers Jan 15 '21 edited Jan 15 '21
If I may be pedantic for a moment... The source code for PowerShell says
$PSItemis an alias for$_:internal const string PSItem = "PSItem"; // simple alias for $_ internal const string Underbar = "_";System.Management.Automation/engine/SpecialVariables.cs line 121-122.
22
u/lcarsadmin Jan 15 '21
Absolutely. Aliases are ok to make your inline typing faster, but saved and documented code should always be full code.
I had no idea $_ was an alias. Learn something every day, i guess
8
u/ka-splam Jan 15 '21 edited Jan 15 '21
It's an alias in the English word definition sense ("another way of saying") but a PowerShell alias is specifically for comand names, and
$_is not one; it doesn't show up inGet-Alias, you can't remove it, etc.16
u/squanchmyrick Jan 15 '21
$_ actually represents the current object in the pipeline. It is an automatic variable, not an alias.
1
u/psthreathunter Jan 19 '21
Not true according to the documentation. See Get-Help about_automatic_variables. Challenge take any of your scripts and do a find/replace and change every instance of $_ to $PSITem. It should work just fine. :)
2
u/squanchmyrick Jan 19 '21
According to the same document you just referenced:
$_
Same as $PSItem. Contains the current object in the pipeline object.
SOURCE: MS Docs about_automatic_variables
Same as $PSItem, but that doesn't actually mean it's an alias for it. Just that it does the same thing.
0
Jan 15 '21
[deleted]
4
u/neztach Jan 16 '21
I’ve never heard the expression syntactic sugar, so I looked it up. I love this term. Thank you for the new term! I salute you
2
u/squanchmyrick Jan 18 '21
Per MS docs:
Assignment Operators
Use assignment operators (=, +=, -=, *=, /=, %=
) to assign, change, or append values to variables. You can combine arithmetic operators with assignment to assign the result of the arithmetic operation to a variable.For more information, see about_Assignment_Operators.
Unary Operators
Use unary operators to increment or decrement variables or object properties and to set integers to positive or negative numbers. For example, to increment the variable $a from 9 to 10, you type $a++.
SOURCE: MS Docs - about_Operators
So you see, while those two look the same they are actually different operations.
-4
u/squanchmyrick Jan 15 '21
Not quite. What you have there is actually two different operations. In the first, you are redefining the variable explicitly. In the second, you are telling PS to simply increment the value of $i by +1.
-1
u/Shty_Dev Jan 16 '21
i have no reason to, but i fucking hate that phrase
i also hate when people say "to piggy back off of ___"
i also hate a lot of other phrases for no reason but im sure nobody cares
4
2
u/Cholsonic Jan 16 '21
I have an irrational hate when people say disorientated instead of disoriented. I know they are both valid words and all but it sounds bad to my ears.
1
0
9
8
u/PinchesTheCrab Jan 15 '21
one alias that I ALWAYS see used is $_ this is actually an alias for $PSItemThis the one point I disagree on. The shops I've worked at still have the odd PS 1.0 or 2.0 server/workstation out there, so I think it's fine to use $_ if you're helping someone whose environment you don't know.
That being said, I use PSItem myself because when I was starting it was impossible to google $_, and even though you can google it now, I just think $PSItem is less cryptic for newcomers.
6
u/jantari Jan 16 '21
And I'll always use
$_because it sticks out much more visually.$PSItemcould be any ordinary variable and is not as easily distinguished when glancing over code.It's just a matter of preference these days that PS1.0 and 2.0 are out of support
3
u/dontmessyourself Jan 15 '21
I never knew about $PSItem but I think that's mostly because VS Code doesn't flag it like it does % and ? and Select etc.
3
u/TheEdonReddit Jan 15 '21
Well... I learned a thing today. I didn’t know $_ was an alias. I usually learn when VS Code warns me.
9
u/dextersgenius Jan 16 '21 edited Jan 16 '21
It's not. OP is mistaken, $_ is the original and $PSItem is the alias.
If you check PowerShell's source code, a comment on line 121 of SpecialVariables.cs says $PSItem is an alias for $_:
internal const string PSItem = "PSItem"; // simple alias for $_In fact, $_ existed since PowerShell v1, and $PSItem was only introduced from v3, as an easier-to-understand alternative to $_. The PowerShell Team clearly state this here:
Some people see $_ as a magic symbol. To help those people, we introduced an alias for $_.
https://devblogs.microsoft.com/powershell/new-v3-language-features/
Just because someone teaches something for a living doesn't mean they're always correct. :)
2
u/MonkeyNin Jan 16 '21
You can configure VS Code to automatically convert aliases like
lstoGet-ChildItem1
u/tombs_4 Jan 15 '21
I had no idea that was an alias. My pretentious "this code isn't following best readability practices" just got stronger. Thank you
3
u/dextersgenius Jan 16 '21 edited Jan 16 '21
Actually, $PSItem is the alias. See https://www.reddit.com/r/PowerShell/comments/ky125k/_/gjesxep
1
1
u/MrPatch Jan 16 '21
what is $PSItem when they see it not realizing they have been using it for
daysyears inclassproduction.
9
u/fuzzylumpkinsbc Jan 15 '21
I think it's a valid point to encourage not using aliases etc, but are we really gonna complain when someone takes from their own time to help us?
If that makes the difference between someone actually helping or feeling like he doesn't want to put in the extra effort to writing 'properly' I'll take the help. Heck there's people writing pseudo code from their mobile phones but it does put you on the right path so to me any help is good help.
-2
u/Pauley0 Jan 16 '21
If you're going to spend your time to help someone who is pretty new, are you going to solve the problem for them in a way that's difficult to understand, or spend an extra couple minutes typing things out (mostly just hitting Tab) so they can learn from your code?
8
u/ka-splam Jan 15 '21
Everybody changes ? {} into where-object {} but almost nobody ever complains about -FilterScript being missing?
2
u/Betterthangoku Jan 16 '21 edited Jan 16 '21
Preach! And Foreach-Object gets a pass for -begin -process -end
edit: Missing Begin, Proccess, and End scriptblocks in an advanced function also get my goat . :-)
1
u/jimb2 Jan 15 '21
99.5% of use cases.
1
u/ka-splam Jan 15 '21
Poking a hole in the claim "things should be written fully specified because it's more readable to others" and revealing it to be "things should be written how I learned them because that's what I do".
3
u/jimb2 Jan 15 '21
No. Where-Object {} is totally standard usage. It's actually quite hard to find code that uses the alternative forms of where-object. If you google it you get it. Try googling %.
OP was suggesting a presentation that works for all including inexperienced users to make things work better, not demanding that everything is written as long and abstrusely as is technically possible. Neither was he saying do it my way.
4
u/ka-splam Jan 16 '21
not demanding that everything is written as long and abstrusely as is technically possible.
Maybe not OP, but the current most upvoted comment says "It is important to write code out in the most verbose fashion so it is easier to read.".
a presentation that works for all
Except people who don't want to read a pile of wordy loops and filters to understand the point of the code, which they are obscuring with noise and fluff.
That aside, why would you ever be googling for
Where-Object? That's part of my complaint about it, you never care for "code which is doing some filtering" because almost all code is doing some filtering and that wouldn't narrow anything down. It's so common, so boilerplate, it's everywhere. If anything should be shortened and symbolic it should be the things that are common, repetitive, samey. The same way you accept*instead ofmultiplyand{instead ofBEGINwe should accept%instead ofForEach-Object. It's no more confusing than*instead ofmultiply, it isn't even the multiply symbol from school math (×) or from matrix math (·) or from algebra (put two things next to each other), and yet everyone is fine witha * b, you don't complain that you can't google*because you never want to google*.You can, however,
get-help %to find out what it is, orget-command %orget-alias %.2
u/Pauley0 Jan 16 '21
My keyboard doesn't have a × or · button on it. And PowerShell doesn't understand them either.
PS > 5*5 25 PS > 5×5 5×5 : The term '5×5' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + 5×5 + ~~~ + CategoryInfo : ObjectNotFound: (5×5:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS > 5·5 5·5 : The term '5·5' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + 5·5 + ~~~ + CategoryInfo : ObjectNotFound: (5·5:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException3
u/ka-splam Jan 16 '21 edited Jan 16 '21
that's my point.
*isn't even the "correct" symbol, and it's /still/ accepted over writing the word. There's no reason that%can't or shouldn't mean a loop, or that it's inherently more difficult or more confusing or less correct than using*for multiplication is.0
u/itasteawesome Jan 16 '21
Except they don't teach every third grader loop programming syntax.
2
u/ka-splam Jan 16 '21
It isn't "loop programming syntax", it's "ALGOL-drivative loop programming syntax". They teach every third grader that you don't need loops you can just say "everyone gets two more apples" and that makes sense, so you make A Programming Language where things work like that (
values = values + 2adds two to each value) and everyone shrugs and goesfor (int i = 0; while i<values.Length; i++) { values[i] = values[i]+2; }"this is the way". And it was the way.
10
u/Zarochi Jan 15 '21
As an advanced user I'd never use an alias in anything anyone is ever going to have to read. It's just poor practice and shows you only care about you and no one else.
I come from Linux land where using alias' is extremely frowned upon because you can't guarantee your script will work elsewhere.
4
u/benjammin9292 Jan 15 '21
Me, 6 months ago: I will definitely remember what this means, no need to write a description
Me, 1 week ago: man who the fuck wrote this shit?
2
5
u/Thotaz Jan 16 '21
I think it depends on the alias, aliases like:
cd
clear
where
foreach
are easy to understand either because they are commonly used in other situations or because the verb is unambiguous. Complaining about those just feels like nitpicking, especially in the context of someone helping you out.
4
u/meeu Jan 15 '21
I like learning about aliases in posts. shrug
3
u/uptimefordays Jan 15 '21
Aliases are fine for use in a shell but if I’m working on code with others or sharing scripts—you’re getting super verbose, commented code, with descriptive variable names. Why? Because I want people using my code to succeed. It makes them look good, it makes me look good.
4
u/lucidhominid Jan 15 '21
Aliases are great because anything that can keep wrist and finger strain at bay is a life saver. That being said, it's not that hard to just do a find and replace to switch all aliases to their full command before giving someone else the code. Leaving aliases in is like handing in a rough draft. Of course, when it comes to getting help from random people willing to help, I wouldn't expect them to be sending you polished code.
2
u/Pauley0 Jan 16 '21
Idunno. If I'm really serious about writing a script, a good chunk of that time is reading documentation, and less typing commands, so it doesn't make that much difference.
3
u/ICanOnlyPickOne Jan 15 '21
Come on now, are you writing 20,000 lines of code a day? Alias won't make a difference to your chances of getting RSI.
2
u/lucidhominid Jan 15 '21
Can't speak to whether it's RSI but it can be extreme uncomfortable by the end of the day. So its less about preventing a condition of some kind and more about diminishing the discomfort being experienced in that moment. Its not like that every day though. I figure its just part of getting old.
3
u/signofzeta Jan 15 '21
Aliases are great in real time. For everything else, such as writing scripts, sharing scripts, or teaching, please follow PSScriptAnalyzer’s advice and wrote it out. (Yes, this means you, too, Where instead of Where-Object.)
3
u/zenyl Jan 16 '21
With PowerShell now being cross-platform compatible, some of the aliases that're presumably designed to make it easier for *NIX users to pick up PowerShell, aren't guaranteed to work even on "vanilla" systems.
By default, using ls on Windows will map onto Get-ChildItem, however if you use ls in PowerShell on Linux, you're actually calling the lsCLI tool, rather than Get-ChildItem.
3
u/dverbern Jan 16 '21
I agree with this post, very much agree. I think aliases are fine for those who are highly experienced and for whom a script is for internal use, but I think for almost all other circumstances aliases can be exclusive, in that they reduce the comprehension of those less familiar with the scripting language.
While I'm at it, I'd love if it fellow gurus started using the standard of "$PSItem" over the old standard, "$_". It's just a minor thing.
Probably the most frequently-aliased cmdlet I see is "%" standing in for "ForEach-Object", but there are a few that pop up.
5
u/AGuyAndHisCat Jan 15 '21
And here I thought you meant DNS aliases
9
2
Jan 15 '21
You are 100% correct.
But also I use common aliases constantly. Gci, ?, cls are 💯. Even for is an alias isn't it?
1
u/bertiethewanderer Jan 15 '21
For is a separate, distinct construct.
1
Jan 15 '21
I hadn't really thought about it, but then I was assuming it's probably an alias for for-eachobject. Like %. Syntax is different though so yeah
0
u/jantari Jan 16 '21
The
forloop is a programming classic, unchanged sinceCintroduced it in the 1970s. It very much predates all of PowerShell or the concept of "objects"1
Jan 16 '21 edited Jan 16 '21
I'm well aware.
Many of the aliases in Powershell are for commands that predate it.
2
u/get-postanote Jan 15 '21
Yeppers, we've all had this chat many times here and other Q&A sites:
See these Reddit Q&As
2
u/bertiethewanderer Jan 15 '21
I'm with you OP. I know my fair share of aliases, and it's been a long time since I had to Google one.
Last thing before I commit anything Powershell is Ctrl+shift+P > Expand Alias.
Because there's plenty of guys in the org who could stumble into this one day, and it took me less than a second to fix.
2
u/pokemiss Jan 16 '21
When I started, it took me quite a while to realise that I was getting the wrong output from my pipelines because I was confusing % for ?. Writing them out saved a lot of confusion.
2
u/jpking17 Jan 16 '21
Tried to get our developers to stop using an alias for 6 years now with no luck
2
u/dasookwat Jan 16 '21
there are only a few aliases like that, and they're used in code a lot. I simple google command would tell you what it does, most decent ide's like vs code also warn you, that you're using an alias, so imo this is not really an issue.
What is far more tricky to learn, is when people start coding in 'dialects'
Like a c# programmer who just formats everything like it's c# in powershell, or things like
($inputvar) -and (do stuff) It works, but it's not easy to read when you're just starting.
Personally, i try to write all my code with the idea, that i love my free time. Meaning: if i make it hard to read, and something breaks during my holliday, i will get called, which i hate.
2
u/MonkeyNin Jan 16 '21
If you have VS Code it automatically converts aliases. You don't even have to save it, just paste it.
3
u/BlackV Jan 15 '21
they sure do, this has been a big problem for a long time (I think there is even a sound bite or Mr Snover saying he regrets alias's)
but stick this in your profile :)
Remove-Item -Path alias:\ -Recursep.s. thank goodness for resolve-alias feature in vscode
3
u/jdtrouble Jan 15 '21
It's not only a nice thing to do, it's recognized as a best practice to use full cmdlet names and named parameters in scripts. As an experienced writer, I don't want to go look up cpp or spsv. I don't want to use the wrong foreach either.
I only use aliases and positional parameters when running freehand commands. Any other time I expand everything out for readability.
3
u/keith_mg Jan 15 '21
I can see where you're coming from with most aliases, but % and ? are so ubiquitous I think they should get a pass. When I was learning (a long time ago 😬) I remember being surprised to find out they were aliases.
3
u/jimb2 Jan 15 '21
Ha, I'm never sure what these thing mean. I write a lot of PS, but it's usually scripts less command line and I prefer everything explicit, well formatted and commented. I should commit them to memory I guess.
2
2
u/SM_DEV Jan 16 '21
It seems to me that the answer to IP’s problem is to learn the common aliases, such that even if OP chooses not to use them, they can still be recognized.
If you are reading the product of someone else, who has taken the time and effort to produce it, especially if you are the one LEARNING from it, then you should just be grateful that someone shared... because I can assure you that it is just as easy to keep your code to yourself.
0
u/poshftw Jan 15 '21
. Many (most?) of the questions here (and other forums) are from posters that are new to Powershell
Hi! My name is Johnny and I'm new to piloting the newest Bingo 999-400 airplane.
I didn't bothered to even read the Quick Start guide, so please, describe me how to operate this plane in the terms understandable even to a 5 y.o. kid.
1
u/Shamalamadindong Jan 16 '21
More like "hey I took a few lessons and I can taxi now but this next instruction someone put up is using a joystick instead of a yoke"
1
u/poshftw Jan 16 '21
It is more like 'Hey, I need to program a LOB app for a Fortune 100 company, what
+in2 + 2means?'1
u/bobthewonderdog Jan 15 '21
yes, but also no. Johnny gets told kindly to fuck off and RTFM. This is after it passes the sniff test, and OP is right
2
Jan 15 '21
[removed] — view removed comment
2
u/Crully Jan 15 '21
Yeah, not like I'm going to end up relying on this script, other people will find it useful and start using it, or build it into the automation packs and builds. And it'll stop working in approx two years time.
20
u/TheKojukinator Jan 15 '21
I like using aliases in the shell to do one-off stuff or to prototype pieces of more complex code that is going into a script. But anything that gets committed to my git repos is fully expanded without an alias in sight.