11 ms·
I have written a lot of Powershell in the last few years. I eschew the clever powershell ways of doing things if someone else may end up owning it (think: wher
by RajT88 4y ago
I have written a lot of Powershell in the last few years. I eschew the clever powershell ways of doing things if someone else may end up owning it (think: where-object, foreach-object) in favor of expressions that resemble other languages (foreach, for).
If I'm writing it for myself, and only ever myself, I'll use the more clever powershell ways of doing things. Expressions like:
1..10 | % {$_}
If you're coming from another language, you're going to have to run it to understand it, or look it up. That is time lost.
- ParetoOptimal 4y agoSome things are short and self explanatory though. `1..10` is just syntax sugar for a stream or list from 1-10 right?
- RajT88 4y ago1..10 is powershell range operator, and % is an alias for foreach-object.
- blown_gasket 4y agoI primarily write in PowerShell for end-user shell tools and Go for network services. Where-Object is going to let you cut down on the number of lines of code compared to foreach() and for(), and in my opinion will make the code more readable. $vms | Where-Object -Property Name -match "sql" vs $vmOutput = @() for($i = 0; $i -lt $vms.count; $i++) { if($i.Name -match "sql"){ $vmOutput += $i } } vs $vmOutput = @() foreach($vm in $vms){ if($vm.Name -match "sql"){ $vmOutput += $vm } } For the Foreach-Object point, that cmdlet also give you the option to use begin{}, process{} and end{} blocks. So that you can with begin{} do something before any of your objects are processed, process your objects with process{}, and after all objects have been process do something with end{}. This logic with for and foreach would have to come before and after the for and foreach statements. I don't see this as a "PowerShell being clever" but more as a PowerShell is a shell that uses pipelines like nix shells but it has everything as an object unlike nix shells. So you get to take advantage of that.
- PeterWhittaker 4y ago> PowerShell is a shell that uses pipelines like nix shells but it has everything as an object unlike nix shells. So you get to take advantage of that. That was one of my favourite PWSH features when I was using it regularly. I’m a UNIX CLI-and-filter guy from way back and after using PWSH for a while I longed for the same power in bash (my shell for reasons of history, availability, and muscle memory, I’m unlikely to change).