by neves · 2y ago · 0 comments
What is the experience of other developers who are experts in both shells to compare them? Did PowerShell really fulfill the promise of being a more efficient and modern shell? Or people just use it because it is already installed and better than CMD?
http://mywiki.wooledge.org/BashPitfalls
I used Powershell recently and not having to wrangle with text (commands return objects) makes it a much easier scripting language, and command line language.
The fact that they have an official way to handle argument parsing is excellent, everything is unified and the commandline window is able to have autocompletion for literally every option of everything. Bash could never even dream of having that. It is incredible and makes you extremely productive.
But type coercion manages to introduce new ways to create bugs that Bash didn't have.
Honestly at this point I prefer PWSH but still kinda dislike both. I'm waiting for the new natural evolution.
This is a great list of pitfalls, absolutely, but they are more an argument for integrating shellcheck into your IDE than avoiding bash, IMHO!
I know, I know, possible religious war, but I find that bash+shellcheck is far more often the right toolset than switching languages to avoid the pitfalls.
The immense power and expressiveness and immediacy of bash makes so many programs and so much prototype->PoC->MVP progression so easy and effortless that it is worthwhile having tooling to catch the worst of the warts.
A 50-line awk script though? Get outta here with that lol
(and I don't recommend it for others because if we're looking at it realistically, most people who trust themselves shouldn't trust themselves)
Which language is that?
I know it ends up in the same terminology bucket for the public consciousness as "CLI stuff", but there is a separation and understanding this separation is crucial for writing good sh.
The problem actually lies in bash+coreutils being some sort of de-facto standard for command line stuff. The way bash+coreutils evolved was mostly for autotools and not for humans. This ecosystem could be much better.
PowerShell has more builtins, so it relies less on external commands, therefore it is less vulnerable to pitfalls due to mismatches between different programs.
But in the end really it doesn't matter in whose end of the kingdom the bugs come from. What matters is that's how people write Bash.
Try this exercise: make a .BAT invoke a powershell script that invokes another .BAT passing parameters containing double quotes inside. It just can't be done reliably. The .BAT is only just an example, any param passing to/from powershell (outside powershells internals) is a nightmare.
In bash, this kind of interaction is commonplace. You can make `find` generate shell snippets for you, and pipe the generate shell commands into another interpreter instance seamlessly.
Think of the sheer amount of software the uses the shell this way and you never notice. That npm script that just passes parameters along is relying on the shell interface, that CI yaml that passes variables is relying on the the shell interface, etc. It runs just for a few milliseconds, to pass and glue things around, super simple. Powershell is just not designed nor suitable for that.
The problem of an uniform interface _can_ be solved by changing how people write stuff. The problem of not fitting well as an architectural piece replacement is much more difficult to overcome. Powershell fits Windows though, but that's about it.
For example: find potential file duplicates in a folder, recursively, by grouping by file size:
Get-ChildItem -File -Recurse | Group-Object -Property Length | Where-Object { $_.Count -gt 1 } | Sort-Object -Property Count
No need to remember arcane `file` incantations, no need to parse textual output. You get real objects with properties, and tab completion can see their structure.Need to parse JSON? No need to involve `jq`, just `Get-Content -Raw whatever.json | ConvertFrom-Json` and do it directly from PowerShell. Need to convert XML into CSV? ConvertFrom-Xml (or Select-Xml) -> do stuff -> ConvertTo-Csv.
Is `Get-ChildItem` too much typing? Use `gci`, or `dir`, or `ls` (by default only on Windows). Is `Where-Object` too much? Try `where` or `?`. And things are case-insensitive.
... | Where-Object Count -gt 1 | ...
Or, of course, ... | ? count -gt 1 | ...There's a lot of
nix aliases for Powershell commands. Get-ChildItem is also called with ls, mv calls Move-Item, cd calls Set-Location, etc. They made at least some effort to make it more accessible to people coming from *nix or cmd.Several years ago, I had to write a complex unattended robust data transfer system in PowerShell. (I know, I know, without more info these “requirements” beg many questions, but they are all out of scope for this reply.)
I enjoyed the experience so much I switched all my shells, on MacOS (my DD) and on Linux (my most common work environments) to PWSH.
What I liked most about it was the power of passing objects in pipelines, and being able to extract/manipulate some of the properties of an object in the first filter and still have access to others, along with those of objects created by that first filter, in filters later in the pipeline.
Immensely powerful.
The consistency of commands, of error handling, and of object properties was also very nice.
Eventually, as the nature of work changed I switched all shells back to bash, as the older muscle memory asserted itself. PWSH as a shell made sense when I was working and thinking so much in that space, but when I left it, it was more effortful to think in PWSH than to resume bash.
There are times I miss it. There is nothing else in the shell space that comes close, or at least not close enough to justify the effort of switching.
gci | select *, @{L='Hash'; E={ ($_ | Get-FileHash).Hash }}
Get-ChildItem |
Select-Object -Property FullName, CreationTime, Length,
@{Label='Hash'; Expression={ ($_ | get-filehash).Hash}}
but even then you could do what you want with a traditional loop and no pipeline: $results = foreach ($file in get-childitem) {
# a hashtable of things you want to be
# in each object ('row') of the output:
$data = @{
Name = $file.Name
SizeGB = $file.Length / 1GB
Hash = ($file | Get-FileHash).Hash
}
[pscustomobject]$data
}I feel like my PowerShell struggles are really about not knowing 2-5 core, general-purpose pipelining commands well enough to use in any situation.
Select-Object - Pick out specific fields from an object, create calculated fields etc.
Where-Object - Drop non-matching objects from the rest of the pipeline.
Group-Object - Cluster objects into groups based on a shared property value.
Sort-Object - Order an array of objects based on a property value.
Get-Content - Read from a file.
ConvertFrom-(CSV/JSON) - Parse a json/csv formatted string into a powershell object.
ConvertTo-(CSV/JSON) - Serialise a powershell object into a csv/json string.
(Parallel)ForEach-Object - Loop over each item in the pipeline, performing one or more actions on it. Usually occurs at the end of the pipeline, or when you need to call an executable that can't handle pipeline input.
One thing I struggled with in the beginning, was not knowing what properties an object might have. You can pipe any object into `Get-Member` and it'll list its available properties and methods.
Many of the "-Object" commands support the use of script blocks if you need to carry out more complex filtering/projection.
|? PropertyName -gt 5 # where-object filter numbers
|? PropertyName -match 'text' # where-object filter text
|? {$_.thing ...} # where-object filter script
|% PropertyName # same as select-object -expandproperty propertyname
|% { $_.thing } # foreach loop
|sort
|sort prop1, prop2
|sort {$_.Name.Substring(0,5) -as [int]} # sort calculated thing
|fl * # format-list , all properties
|ft -auto # format-table, autosize table column widths
|sv q # set-variable -name q, same as $q = <...>
|tee -var q # same but show the results as well as storing in qWhat I do remember is that until I understood what I was trying to do and why (mostly error handling around edge cases, all specific to the app), I couldn’t really grok the various object management calls, but that once I’d done a few rounds of PoCing and RTFMing, everything fell into place.
* Trying to be a .NET language. I don't know why the one-runtime-many-languages promise of .NET withered on the vine while it flowered in Java-land without the promise even having been made, but it did. If you're writing .NET code, use C#. (And I say that having worked in one of the very few teams doing large scale development in F#.)
* Failing to get the basics of being a shell right. I can't remember the details as I've left it firmly in the past now, but its handling of redirection was just broken, to the extent that things that were trivial in bash were nigh on impossible in powershell. I got the impression its developers ignored the things bash etc. did well in their enthusiasm over building something new and powerful.
* Being fetishistic about stuff like requiring Verb-Object naming for everything. It's certainly subjective and has its defenders, but IMO it renders scripts ugly, is awkward to type and doesn't materially improve discoverability or memorability at all.
Edit: And that isn't to say .NET doesn't need a scripting language. It sorely needs that and the various relatively useless variants on "C# scripting" are testament to that. Powershell isn't, and doesn't even attempt to be, a solution to that lack, though.
Why it's .Net is also covered and its probably not what you expect.
(New-Object -ComObject InternetExplorer.Application).Visible = $trueThat said, powershell seems more capable than bash if you know it well, because it has a better type system and arguments are easier to mess with, whereas bash things are amorphous strings.
https://github.com/bionicles/tree_plus/blob/main/tests/more_...
That’s a slightly out of date version of what I use to provision stuff on my windows machine to test things, and can show what’s possible a bit.
It is very good of you want to work with Azure though. You probably don't want to use bash for that. But lots of reading up each time I use it. Bash is my go to for small jobs or a command line experience.
I am not an expert in either but have used both plot to get stuff done.
Windows... You have to wait until someone in WDG decides some existing idea is good and then also wait for them to get support to implement the idea, then wait to see how that whole thing goes. So yeah Powershell is great for interacting with Windows. But Windows thinks you're a dumb shit so you can only do what Windows already lets you do.
It was indispensable when it came out. VBscript and Cygwin were the only options; both of them sucked. The ability to use native .NET objects in scripts was insane; I definitely abused that!
Nowadays, Git Bash and WSL2 replace a lot of the value that PowerShell provided.
It's purpose was to drive Microsoft away from the GUI, and, at that, it more than succeeded.
I'd challenge the Cygwin aspect. With judicious use of cygpath & co., you can go VERY far with Cygwin. I've built an entire SaaS deployment system on top of it (and Python).
So, the experience of PowerShell on Windows is unbeatable... on Windows. It's easily beaten on any other system.
Unfortunately, it also has some real sore points for use as an interactive shell, and even some outright broken behavior. Some that I lament most frequently:
- Powershell has native tab-completion support, but the word-of-god dictated "Verb-Noun" command naming scheme means almost every command shares a common prefix with a slew of entirely unrelated commands, making tab-completion painful.
- Power shell has sparse built-in support for funtional style list manipulation or data structures beyond lists. There's a "map" command (%), but no reduce, zip, tail, etc. These feel like they'd fit in perfectly to the design of the language, but they're just missing. Also, pipes are lazy, but lists are always strict, which can cause friction.
- most operators are strangely named, such as "-eq" for ==, which hurts legibility.
- There're lots of unvoidable brackets, meaning you often need to jump around the line while writing out a command incrementally. For example, to get filenames, you either need to write `(Get-Item).Name` or `Get-Item | %{$_.Name}`. It'd be nice to have something like `Get-Item |. Name` as an option.
- It's impossible to pipe raw bytes between commands/executables; raw bytes are interpreted as strings. This means, for example, it's impossible to pipe a file to `patch`, because the contents will be decoded into strings, piped as strings, then re-encoded with line endings changed, which `patch` rightfully refuses to apply.
- Running Powershell scripts is disabled by default (WTF?)
By comparison, *sh's heavily favor interactive use. For example, you can put io redirections at the start or end of a line, tab-completion is often very good, it's often possible to avoid brackets (ex. with xargs), background/foreground job management, etc.
Overall, I often find Powershell more pleasant to use than *sh, especially when writing scripts. But for interactive use, I often wish Powershell was a little smarter and a little dumber at the same time.
Get-Item | % NamePut another way, you could feel free to parse the output of ls in powershell - because it's already been done for you.
I feel Bash is a 'glue language' in every sense of the word, and is optimised for interactive command-line usage because of its terseness. Being remotely productive on Bash presupposes the presence of an entire UNIX subsystem and coreutils (which is why Git Bash for Windows drags along an entire `/usr/bin` directory with all the coreutils in it). You can't really do much in it without the coreutils.
I find that Bash parseability and ease-of-understanding rapidly deteriorates in scripts of increasing complexity. After about a hundred lines of code I reach for other languages. I personally dislike its unintuitive syntax, global scope, and weak, dynamic typing. The terseness that lends itself to powerful interactive command-line usage means script readability plummets. Of course, that might just mean I'm inexperienced with respect to Bash and need more practice, but I find this a fairly common opinion amongst colleagues and friends. In my opinion, Bash scripts are write-only. It is a wonder that something like neofetch[1]—which is an eleven thousand-line monstrosity—lasted this long (if I recall correctly the author stopped maintaining it because—amongst other reasons—it had just become too complicated).
I find that people understand PowerShell better when they realise it is closer to Python than any interactive UNIX shell. By default, PowerShell is more verbose than Bash; for instance, the PowerShell equivalent of the two-character all-lowercase `ls` is the thirteen-character mixed-case `Get-ChildItem`. Arguments are by default also long and verbose, with things like `-FollowSymlink`. PowerShell is generally meant to be used in executable scripts, just like how most Python isn't executed in the interactive REPL, but by running scripts. Consequently, I find this verbosity lends itself to improved readability in scripts, at the expense of some interactive productivity. That being said, common PowerShell commands have UNIX-like aliases[2] (at one point the cause of much gnashing of teeth here and at /r/programming because PowerShell aliased `curl` to `Invoke-WebRequest`[3]) to improve interactive productivity. PowerShell also supports truncating parameter names; for instance, `Get-ChildItem -Recurse -Force` can be abbreviated to `gci -r -fo`, which looks remarkably like a UNIX command now. Even so, the PowerShell ISE and the PowerShell VS Code extension both suggest that programmers use the full unabbreviated commands and arguments in `.ps1` scripts[4].
PowerShell is also dynamically typed, though semi-static typing can be opted in to[5]. That said there is some controversy about arrays decaying to scalars when they have size 1 [6]. It is easy to set up both function and script parameters with as much power and expressiveness as `argparse` for Python, but natively without involving any additional modules[7].
The real power (pun not entirely unintended) of PowerShell comes when you realise it is just another front-end to the incredibly massive .NET ecosystem. Where Bash requires a full UNIX subsystem and a collection of hundreds of additional binaries to be productive, PowerShell employs pre-compiled cmdlets[8] written in .NET (usually C#) to augment the basic language. Most 'commands' in PowerShell are cmdlets, including `Get-ChildItem`. You can write your own 'back-end' in C#, F#, C++/CLI, VB, or any other .NET language, compile it, and expose a PowerShell interface for end-users. Pretty much like how people write fast but complex code in C/C++, compile it, and expose a Python interface (Numpy, Pandas, PyTorch, etc come to mind). You can additionally directly call .NET methods in PowerShell[9].
This also means that everything in PowerShell is an object. The output of `Get-ChildItem` is a list, not a string. Likewise for `Get-Process` (UNIX equivalent: `top`). These lists may be formatted[10], filtered, parsed, modified, dumped to JSON, and otherwise manipulated like any other list data type in most other languages.
PowerShell also lends itself to the side-effect-free/functional/monadic map-reduce paradigm very well, with pipelines[11].
In my opinion, it is not merely 'better than CMD'; it blows CMD out of the water. A little less so for Bash, because Bash is augmented by the UNIX core-utils. As should now be evident, in my view the real competition to PowerShell is Python.
[1]: https://github.com/dylanaraps/neofetch/blob/master/neofetch
[2]: https://learn.microsoft.com/en-us/powershell/scripting/learn...
[3]: https://news.ycombinator.com/item?id=12319670
[4]: https://learn.microsoft.com/en-gb/powershell/utility-modules...
[5]: https://stackoverflow.com/a/115815/1654223
[5]: https://superuser.com/a/414666/1132163
[7]: https://learn.microsoft.com/en-gb/powershell/module/microsof...
[8]: https://learn.microsoft.com/en-gb/powershell/scripting/power...
[9]: https://devblogs.microsoft.com/scripting/learn-how-to-use-ne...
[10]: https://learn.microsoft.com/en-us/powershell/module/microsof...
[11]: https://learn.microsoft.com/en-gb/powershell/module/microsof...