News for hackers. Stuff that matters.
Re:Want cleaner code? Use the rule of six by RajT88 on Saturday September 24, 2022 @12:28PM (#32964159)
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.

Re:Want cleaner code? Use the rule of six by blown_gasket on Saturday September 24, 2022 @01:14PM (#32964599)
I 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.

Re:Want cleaner code? Use the rule of six by PeterWhittaker on Saturday September 24, 2022 @01:44PM (#32964938)
> 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).

Re:Want cleaner code? Use the rule of six by ParetoOptimal on Saturday September 24, 2022 @12:40PM (#32964283)
Some things are short and self explanatory though. `1..10` is just syntax sugar for a stream or list from 1-10 right?
Re:Want cleaner code? Use the rule of six by RajT88 on Saturday September 24, 2022 @01:09PM (#32964560)
1..10 is powershell range operator, and % is an alias for foreach-object.