Hacker News new | ask | show | jobs
by BoiledCabbage 1980 days ago
The single most underused command in powershell is: Get-Alias

Essentially every command you'd use has a 2 or 3 character alias that is easy to remember and quick to type.

On top of it their almost programitacilly named, so if you know the powershell commands full name you can almost certainly guess the alias

Typing Get-Alias lists them all out.

https://docs.microsoft.com/en-us/powershell/module/microsoft...

6 comments

I now have a burning temptation to write "Get-Alias Get-Alias"

  PS C:\Users\Kuinox> Get-Alias -D Get-Alias

  CommandType     Name                                               Version    Source

  -----------     ----                                               -------    ------

  Alias           gal -> Get-Alias
and I have been told by at least twenty people never to use aliases in powershell scripts so aliases are effectively useless.
I think the idea is that in scripts you should use the full name for maximum clarity and self-documentation; in your own terminal invocations, be as terse as you want.
That is precisely the idea. The verbose names are self-documenting. You need documentation (names, types, comments, etc.) when code will be reused and read and altered at a later time.

Interactive use is different. It is write (and tweak) then use once. You never write comments in the interactive terminal. For interactive use you have aliases, plenty of them.

One reason for that is that other people may have different aliases set up, so you cannot count on your aliases working everywhere. Yes, that also means the default aliases, which may (although very rarely) change from version to version.

For PowerShell ISE there was an extension that automatically expanded all aliases, I believe for the current language server there may be similar things. If all else fails, a PowerShell script can do that as well, since PowerShell exposes its own parser in its API, so a script can easily introspect itself or another script.

If you're working on a shared project where people might care, I usually have the [PSScriptAnalyzer][1] just auto-correct any aliases dynamically for me in my IDE.

If you're just doing a quick one-off or interactively, then who cares! Crack on with your incomprehensible one-liners!

[1]: https://github.com/PowerShell/PSScriptAnalyzer

Powershell gives the best of both worlds: readable command names in scripts, and simple Bash-like shortcuts when you type stuff in the terminal.
Is this really the "best of both worlds" or does this just double the number of commands you have the learn?
Since you don't have to learn the aliases, you can use the full command names in the interactive shell, it doesn't double anything.
Last I heard (and I haven't had direct visibility into this since about 7 years ago) aliases are preserved between versions for backwards compatibility, but you shouldn't use abbreviated parameter names in scripts because there's no guarantee that they won't become ambiguous if more parameters are added to a command.
That is true; but since the aliases and parameter names are discoverable with introspection, if you are writing a script you can have a tool which expands them all to their full name if you want that.

That said, the PowerShell team do care about breaking backwards compatibility, so this risk is more likely in a 3rd party module than in the PS main cmdlets.

Then you just end up with bash commands again, such as "pwd" and "cat"
Yes, you do. With the advantage of the rich object model. Best of both worlds.
And you can still use the full names in scripts (rather than directly in the shell), so you don’t rely on future readers knowing the aliases.
Thanks so much for sharing this!!
Aliases don't have short forms for their arguments, so for any serious command you'd still be typing (tabbing) a lot.
Yes they do. Powershell is smart enough to find the argument as long as it's not ambiguous. For instance:

    Remove-Item -r -fo ./path/to/some/directory
Powershell is smart enough to know that -r means -Recurse and -fo means -Force because the Remove-Item cmdlet has no other parameter that starts with -r. For -f there are two possible arguments: -Filter and -Force which is why you need to be more specific with -fo.
oh god, fuzzy matching
No it's not fuzzy. It's long-enough-prefix-string-to-be-unambiguous.
But possibly not forward compatible for future parameter addition?
Potentially, if someone adds a new parameter which clashes so the prefix you used is not unique. PowerShell 7.x is introducing support for traditional C-style ternary expression "a ? b : c" and there's a potential syntax clash there because PowerShell has always allowed variable names to end in a question mark, e.g. "$isConfigured?" and with that there's no way to stop "$isConfigured? a : b" parsing as a variable name and then an error. The official way forward is to mandate that variable names used with ternary expressions must use the full-brace names like ${isConfigured?}, which is annoying.

People don't want that, but the PowerShell Team are not moving easily to a possible-break of backwards compatibility in how the language parses variable names. It's been discussed here: https://github.com/PowerShell/PowerShell/issues/3240 for dozens of comments, and goes:

"@PowerShell/powershell-committee reviewed this one today, we have a couple thoughts: No matter what we do, we're going to do some analysis of our corpus of scripts to see how often folks use ? in variable names. Some of us have a hypothesis (that others would like to validate) that the users who are using ? in their variable names may be less advanced users (as we agree in this room we'd stay away from it because of the potential problems that could arise). On the other hand, anyone using the functionality described here will be able to understand a slightly more complicated syntax (like ${foo}?.bar). Therefore, we prefer option 3 because it avoids breaking changes on these less experienced users."

The committee ruled to keep the need for ${}, then the ternary expression became a gated experimental feature in PowerShell 7, you have to opt-in to enable it. One of the PowerShell developers analysed the PowerShell Corpus of 400k+ scripts collected by Lee Holmes and Daniel Bohannon for security threat research[2][3] and said "I found that about 62% of variables that have ? in them use it in the end. That made me lean towards not introducing a breaking change." - in the comments on a pull request[4]. Then someone else made another analysis of the corpus with regex and came up with 329 out of 22,000,000 of variables have a potentially clashing "?" at the end.

It's been reopened as another discussion[5] and another person came up with an analysis of the Corpus with proper tokenising/parsing[6] and came up with 11 variables ending in ? out of 1,896,983 unique variables used[6] which then narrowed down to 1 that might break in backwards compatibility if this change happens. Coming up 4 years of back and forth discussion, even with that kind of evidential backing, with 2 core developers, the Team Lead and Bruce Payette one of the original developers weighing in against, being brought up in a community call, then flagged for review by the committee, then reopened as a reminder again[7] the team is still not won over on the risk of breaking backward compatibility by changing ? parsing at the end of a variable name.

That is, yes "possible not forward compatible for future parameter addition", especially by third party modules who might not take it as seriously, but not at all casually by PowerShell's developers.

[2] https://www.fireeye.com/blog/threat-research/2017/07/revoke-...

[3] https://aka.ms/PowerShellCorpus (1.2GB compressed)

[4] https://github.com/PowerShell/PowerShell-RFC/pull/223#discus...

[5] https://github.com/PowerShell/PowerShell/issues/11379

[6] https://github.com/PowerShell/PowerShell/issues/11379#issuec...

[7] https://github.com/PowerShell/PowerShell/issues/14025

For deletion!
You can shorten any argument name in PowerShell, so long as it can be disambiguated:

    PS C:\> ls -di # same as Get-ChildItem -Directory; -d would pass the -Depth parameter instead
    

        Directory: C:\


    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----       2020-07-24     18:09                PerfLogs
    d-r---       2020-12-14     22:45                Program Files
    d-r---       2020-12-24     22:57                Program Files (x86)
    d-----       2020-07-23     11:29                temp
    d-r---       2020-07-24     14:19                Users
    d-----       2021-01-15     21:33                Windows

  > ls -di # same as Get-ChildItem -Directory; -d would pass the -Depth parameter instead
Ouch, that is actually worse than I thought. So not only can you abbreviate parameters, but when the abbreviation is ambiguous Powershell just arbitrarily picks one instead of giving an error?
Alias are nice, but if the short version is not enabled by default, it is mostly useless outside of your normal workstation. During the course of my day I'll be working in many different containers and VMs. All of them 'cattle' so they will only live hours to weeks at most. It just isn't worth creating aliases if I can't use them most of the time.

A long time ago I spent time making alias and using custom shells but over time I just slowly reverted to default bash because it is always there and always works the same.

The aliases he’s talking about are all set by default. Most of them IIRC are just simple abbreviations- for example Get-ChildItem is gci.
I didn't realize the alias were pre-defined and not just user created. Thanks for clearing that up in reasonable way.
What the heck is going on with people on this site (or the internet in general) speaking with absolutely complete confidence in something while also being completely factually wrong?

It used to be that some minor point might be wrong; now it's the entire comment! Premise, conclusion, everything!

Have we gotten this lazy and this overconfident that we think sounding confident is enough? That if we thought it up, it must be true? In a technical discussion? REALLY?!

...I don't want to live on this plane of existence anymore.

Please don't post unsubstantive comments to HN. If another comment is wrong, the thing to do is respond respectfully with correct information. Then everybody can learn something. Please don't respond by fulminating about the community. HN is an internet forum and the internet is replete with people speaking confidently about things they don't know about I'm not saying that was true of the GP but it's certainly true in general—and frankly that's just human nature.

The internet, including HN, is also a frustrating and activating place which triggers all sorts of untrue overgeneralizations after encountering things one dislikes: https://hn.algolia.com/?dateRange=all&page=0&prefix=true&sor...

https://news.ycombinator.com/newsguidelines.html

(Please see https://news.ycombinator.com/item?id=25862346 downthread also.)

The parent comment may be incorrect (I don’t actually know, more on this in a sec), but your comment is not constructive.

https://news.ycombinator.com/newsguidelines.html

Unfortunately, while accusing the parent of being completely wrong, you have not elaborated on how/why.

Would you explain the issue(s) for the parent commenter’s future reference and for those of us who don’t have a deep knowledge of PowerShell?

The comment you refer to seems like it was posted by a machine, or at least a troll. Note it is very generic and could be inserted into ANY discussion-thread. And cleverly it claims to criticize "over confidence" when in fact it itself tries to get its point across by being forcefully confident about its own righteousness. That is an old rhetorical trick accusing others of something you are doing to take the focus away from your own issues. Reminds me of some politicians
Please don't post unsubstantive comments, call names, or take HN threads further into flamewar. All that is against the site guidelines: https://news.ycombinator.com/newsguidelines.html.
I'm not a troll, or a machine, thank you very much.

At this point I can't edit the comment in question, but every assumption in the comment it was a reply to was wrong. Every single one.

Aliases in powershell are not turned off by default. Aliases either exist or they don't. When speaking of aliases alone, bash is no simpler nor more complex than powershell.

By the way, this comment (the one I am writing right now) is ALSO replying to a comment written by someone who appears to be overconfident and under-informed. It's a freaking malady, and people are somehow proud of their incorrect blind guesswork.

Incorrect, blind guesswork gets a pass, because the statements made sound correct to a layman, and sound objections don't get a pass. I understand, now. I wasn't clear on how important facts are in a technical discussion.

I stated no facts in my earlier comment, that's true, but neither did the person I was replying to. I thought my point was clear. It was less clear than the comment based on false assumption, I guess.

I fucking give up. You assholes can have this.

Please don't give up! but please also don't break the site guidelines: https://news.ycombinator.com/newsguidelines.html.

Your two comments in this thread contain one fine, substantive statement: "Aliases in powershell are not turned off by default. Aliases either exist or they don't. When speaking of aliases alone, bash is no simpler nor more complex than powershell." If you had simply replied upthread with that in the fist place, it would have made a fine comment with a very high signal/noise ratio. Unfortunately the rest of both comments is just noise, tanking the ratio.

As I explained upthread (https://news.ycombinator.com/item?id=25862312), the internet is crazy-making this way, but it's not some property specific to HN and it's not something that's somehow changed lately. It's intrinsic to the medium, and we all need to build our skills in coping with it—which includes not reacting from a provoked place. That's not easy, but it's necessary to the sort of community we're trying for here, and we need everyone to work together on that.

Don't give up don't give up. It's just that if you think about it your original comment is written in a way that it could be injected into most any discussion-thread on social media as is, and therefore I found it quite amazing in its construction :-)
How is my comment wrong? I said `if the short version is not enabled by default..` which suggests that I do not think they are but am not 100% sure. Ok, I was wrong and rest of my critic doesn't apply but how is this suddenly translate to `I don't want to live on this plane of existence anymore.`? I was just wrong in assuming that aliases were user defined like on most shells.