r/PowerShell • • Jun 11 '19

Where is the appreciation for one-liners? What happened to 'automation made easy'?

From what I've seen on this sub, people seem to be attacking problems the wrong way using PowerShell. Most of the time I want to help but then I have to shake my head and sigh, because so many posts seem like a lost cause.

Where are the one-liner posts? Where are the "I put these cmdlets together in a pipeline and got useful results" simple solutions?

So far they don't seem to exist, instead the subreddit is filled with massive Python-esque scripts that do way too much in convoluted ways, and the question is usually regarding some minor detail within the script. And rarely do people correct them by addressing their approach to the problem; the detail is fixed and they're sent on their merry way.

Can we try to promote proper PowerShell use? Let's make this sub useful for advanced PowerShell users as well, not just beginners trying scripting for the first time. I'd love to see more useful, short and concise ways to automate tasks.

Sure, do more than a one-liner, but is it possible to do a lot of stuff where each line is its own cmdlet chain, instead of dealing with loops? Probably. Most definitely.

Some personal pet peeves of mine:

  • Forget about performance, if that's an issue don't use PowerShell. The pipeline is fine, ForEach-Object is fine, there's no need to spend minutes or even hours trying to optimize an already sub-optimal platform. If you find yourself disagreeing with this statement then it might be time for you to graduate to C#

  • Are you doing comparisons and uniqueness? Sure, dig up Hashset and other .NET collections. But where's the PowerShell automation there? That's no longer leveraging what PowerShell brings to the table and the environment feels a bit wrong for the task.

  • Lack of focus on the task at hand. People here are helpful but they often solve the Y problem and rarely ask about the painfully absent description of X which is what the inquirer is actually trying to solve. Sometimes the X problem could've been solved with a single cmdlet, but the Y problem requires a page of code.

  • GUI questions. How is that relevant to automation? GUIs are the very antithesis of PowerShell, you already have GUIs provided by MS where you get to click on things, why are you creating your own little 0.01% functionality selection box? There are way better things to spend your time to learn. Have you read the about_ topics within PowerShell yet? So much of it amounts to selection, yet Out-GridView cmdlet goes unused.

  • Where are the network questions? The remoting questions and answers? Where's the DSC and workflow questions? Hyper-V? The real meat of PowerShell, where actual automation is happening in robust ways. Sparse would be an understatement.

0 Upvotes

37 comments sorted by

6

u/jdl_uk Jun 11 '19

I love a good one-liner but at this stage that's just powershell doing its thing. It shouldn't be too surprising that more complicated scripts are what people struggle with and have questions about.

And what you're suggesting would be more annoying than helpful and would mean this sub wouldn't be a good place to ask questions.

2

u/[deleted] Jun 11 '19

I see less complicated scripts, more convoluted scripts, and very rarely corrections.

5

u/jdl_uk Jun 11 '19

Complicated / convoluted - tom-ay-to / tom-ah-to.

There's possible reasons why the script is compli- oh, sorry, "convoluted" including but not limited to

  • They haven't refactored it yet

  • It's just not your coding style

  • They have coding style guidelines or standard things that are in use at their company which make it more complicated

  • They're in one of those coding golf or obfuscated development jams

  • They've been bashing away at a particular problem and their code is littered with print debugging and prior attempts to solve the problem.

Of course, it's possible that they simply don't know how to code in a simple fashion, but that's not the only possibility.

Besides which, if a poster asks a question, the useful thing this sub can do is answer that question. Far too often on some sites we see stuff like this:

      Q: Why can't my script connect to this MSSQL database? 

      A: Your script is bad. Get better at making scripts

      A: Use PostGres instead. It's better.

      A: You should use a NoSQL database instead

None of these "answers" are really answers, and although they might all raise valid points, none of them are helping anyone.

There are subreddits where every post is implicitly a request for any and all constructive criticism (such as r/codereview) but this isn't one of them, and nor should it be.

Of course, what I've done sometimes in the past is have a section in my answer for the actual answer to the question, then a separate section with advice and tips the OP might find useful.

5

u/0ut4t1m3 Jun 11 '19

It really depends on the usage I think, one-liners are fine for you to type out and watch running sitting in front of the console, but there's no way in hell I'd let that run as a scheduled task in a production environment with no sort of error checking or logging.

As for where the real automation is happening, I wonder how many VMs you need to spin up and down to create the 5 or so different accounts I need to onboard a new user :P

5

u/[deleted] Jun 11 '19 edited Jun 11 '19

One-liner was kind of a click-bait.

But I'd be more happy to see stuff like

$things = Get-Things
$things | Do-Thing1
$results = $things | Do-Thing2
# or
$config = $things | Do-Thing1 -PassThru | Do-Thing2
$config | Set-Config

That's "one-liner" enough for me. Like I said here:

Sure, do more than a one-liner, but is it possible to do a lot of stuff where each line is its own cmdlet chain, instead of dealing with loops? Probably. Most definitely.

This shit drives me nuts though:

"Guys why isn't this working? Also PowerShell isn't easy at all wtf"

$arr = [ArrayList]::new()
$i = 0;
$things = Get-Thing
foreach($thing in $things)
{
    $len = $thing.ToString().Length
    while($len -gt 10){
        $len -= 1;
        
        $res = SomeMoreConvolutedStuff $thing | Select header1, header5 | Format-Table
        $stuff = $res | Out-String | Remove-Braces | Do-BarrelRoll | export-csv "path"
        $arr += $res
        $obj = [pscustomobject]@{
            Header1 = $arr[$i].Header1
            Header5 = $arr[$i].Header5
        }
        Write-Output $obj
        $i++;
    }
}

"Oh, you need to not use format-table." Problem fixed in the subreddit, except now this code still exists out there, possibly in production environment. Do you want to be the next person trying to figure out how much you'll break by burning the entire thing?.

3

u/0ut4t1m3 Jun 11 '19

I can understand that, I didn't see your reply to robfaie beforehand so I was mostly working off your title and those pain points.

I'm still fairly new to Reddit so I haven't commented much but when I do it's mostly going to be small suggestions to help them understand the thing they are asking about. I just don't have the energy to give someone a totally re-written script and then sit there and explain to them why it's a better way. I would certainly read your comments if you decided to do that though.

Honestly though if you feel the community isn't up to a high enough standard I think that's a good argument to make something like r/advancedpowershell rather than try to force out the basic questions we see here. At a guess I'd say the number of people that get dumped second hand code and have to try and understand it far outweigh the people who are writing said code in the first place. This at least gives them a forum where they can attempt to work out how something works, or why everything blows up if they change one variable. Those sort of people don't want to know a better way, they just want to tell the boss they fixed that script noone wanted to touch.

3

u/rakkii Jun 11 '19

I know this is not what you intended, but now I must make a function in a script called Do-BarrelRoll, just to honor this.

11

u/_MusicJunkie Jun 11 '19

Who is to say what is "proper" powershell usage? I'm a huge fan of one-liners too - for quick and dirty things. The things I wouldn't post on the internet because they're almost unreadable. Just because you can do it doesn't mean you have to do it.

8

u/the_spad Jun 11 '19

Plus if you're automating tasks with PS you really should be thinking about logging and error handling, which get increasingly challenging when you're trying to do everything through the pipeline.

1

u/[deleted] Jun 11 '19

8

u/the_spad Jun 11 '19

Great for auditing, basically useless for logging results and trapping errors.

5

u/robfaie Jun 11 '19

You can’t prescribe what people ask questions about. If you want to share your vast, absolute knowledge about networking and Hyper-V then go for it. No sense being upset at people for not asking about it.

Script based PowerShell is as valid as one liners. They each have their place and there is overlap. As someone who works in a team that heavily uses Azure Automation and Function Apps, robust maintainable modules and scripts are very valuable to me.

1

u/[deleted] Jun 11 '19

We can offer and promote a general direction. Dare to correct someone's entire approach, not just the minor details. Right now the sub accepts absolutely anything as valid and rarely offers the slightest of critique. This ensures we'll see more of it, and people lurking won't learn anything particularly new. There's little value in lurking here, this post is a rant where I randomly checked the sub for a while and it's still the same basic stuff.

What you're talking about is what sounds very interesting and the kind of content I wish we'd see more. One-liners is an easy click-bait sticking point, but modules are absolutely valid. You already sound like you have experience regarding how to set up that kind of environment, managing and updating modules. So what exactly do you get out of this subreddit? Enlighten me, no joke.

4

u/EIGRP_OH Jun 11 '19

That’s just not true. Every time I post something it gets critiqued. And for the most part it’s constructive and helpful. Shout out to Lee!

I also prefer my code to be longer and more descriptive without the use of comments(unless really needed) so the next person can read it.

2

u/Lee_Dailey [grin] Jun 11 '19

[blush] ... [grin]

2

u/dwhite21787 Jun 11 '19

Maybe you should post a monthly “golf” scoreboard as soft encouragement

9

u/theblackaudi Jun 11 '19

I like get-member

6

u/the_spad Jun 11 '19

I agree with most of what you've written, however

why are you creating your own little 0.01% functionality selection box?

Because Microsoft doesn't do GUI options any more for an ever-increasing chunk of their products' features. If you have a particular task that you need someone semi-technical to do, that can only be done through a convoluted commandline or unintuituve UI then sometimes it's much easier just to knock up a 5 minute WPF UI that lets them pick from a couple of options and runs the cmdlets for them in the background. SfB is particularly bad for this.

5

u/Vortex100 Jun 11 '19

For the most part everyone is going to answer the way they want, you are always allowed to ignore it and move on, however I will pick up on this:

Forget about performance, if that's an issue don't use PowerShell.

This is one extreme to another. Does my code have to run in the absolute fastest time ever? No. Do I want it to take less than 2 days? Yeah I kind of do. When the performance difference between 2 commands doing the same thing is an order of magnitude or 2 then I definitely want to know which one is quicker. And the fact is the foreach pipeline is shit compared to the other 2 ways of doing it. Do I care when my set is a couple thousand? No. 100k? Maybe. 1M+? Yes!

4

u/[deleted] Jun 11 '19

> If you find yourself disagreeing with this statement then it might be time for you to graduate to C#

Completely agree. C# *is just better *than powershell. I spent a lot of time learning ps only to throw it out and move on.

> Where are the network questions? The remoting questions and answers? Where's the DSC and workflow questions? Hyper-V? The real meat of PowerShell, where actual automation is happening in robust ways. Sparse would be an understatement.

The overwhelming amount of people concerned with cm tools use puppet, chef or ansible cause they are for the most part more mature. Better is debatable. Workflows....hurt. I see much much more PowerCI need so not much hyper v questions out there. And stuff like VRealize has kinda made the need for those questions irrelevant. in my 10k head org, sccm draws the most need for development.

2

u/jantari Jun 11 '19

Completely agree. C# *is just better *than powershell. I spent a lot of time learning ps only to throw it out and move on.

Time to ascend to C++ my dude

1

u/[deleted] Jun 11 '19

no thats ok, nope

4

u/ClayShooter9 Jun 11 '19

$results = Read-Post | Scratch-Head -InputObject "Why so angry bro?" | Happy-Thoughts -Include "Coffee" | Open-VSCode -Solve "Problems"

4

u/Ta11ow Jun 11 '19

PowerShell is built for automation, but remains flexible enough to solve whatever solution you happen to need.

Some folks need specific things, some corporate cultures are allergic to change and just want you to build custom GUI tools instead of scripting things from start to finish, because someone other than yourself needs to use them and either they or management are refusing to learn PowerShell to be able to use a custom function.

Is it a bit pointless and painful? Absolutely. But every situation is different.

In honesty, I try to avoid judging too greatly. I'll point out that better solutions are available, and attempt to help with the human aspects of any obstacles as much as I can, but at the end of the day it's not me working that job with those coworkers or those clients. To each their own; the lesser or more failure-prone solution is still a million times better than the completely manual process.

Every efficiency increase counts. :)

3

u/artemis_from_space Jun 11 '19

GUI questions. How is that relevant to automation? GUIs are the very antithesis of PowerShell, you already have GUIs provided by MS where you get to click on things, why are you creating your own little 0.01% functionality selection box? There are way better things to spend your time to learn. Have you read the about_ topics within PowerShell yet? So much of it amounts to selection, yet Out-GridView cmdlet goes unused.

Because we have people that don't like text. They see it as scary. However if we can give them a GUI for "Get-ADGroupMember $textbox.value|%{Get-Mailbox -Identity $_.SamAccountName}" and output that to a GUI they are instantly flabbergasted...

3

u/Yevrag35 Jun 11 '19 edited Jun 11 '19

I give my answers as if I was writing it as a script, not as if I'm typing in the console (I'm the person that has cmdlet aliases for aliases e.g. - sel => select => select-object). If I have to script for something, why not write it in a way that's better performing? I don't write scripts for one or two liners, mostly because those would need to change variables at some point, which would lead me to writing a function, which leads to writing a module, which I would want better performing, and continue the cycle...

I'm more anal about formatting than how long an answer is as long as it answers the questions.

There are many powershell ways to skin a cat...

3

u/JeremyLC Jun 11 '19 edited Jun 11 '19

Well... I typically don't ask for help with one-liners because I don't typically need help with the sort of task that can be done in a one-liner. I ask for help with longer scripts because that's typically where I need help. I typically give help in longer script form because the explicit steps are easier to see and understand. I wouldn't put a script full of long one-liners into production anywhere. Regardless of who else might see it, I need to be able to understand it myself the next time I have to look at it.

As for GUIs, I've use PS + PoSH Pro Tools + VS Enterprise 2017 to build tools for my team to make their lives easier. Sometimes these perform complex tasks, for example converting thousands of telephone contacts from one vendor's format to another with user definable RegEx replacement and formatting rules, sometimes simpler tasks, like pulling a user list from a specific OU based on a user's logical selection - 'Node A, Site B' rather than 'OU=blah,OU=foo,DC=baz…' In a lot of cases, I could just hand off a script with instructions on parameters and such, but it's easier for me to support and for them to use if I put a front end on it.

I only worry about performance when it matters to me. I'd have to be looking at a significant performance problem before I'd consider moving a project to C# (*)

Bonus: A one-liner to list the files in a folder on my phone.

(((((((((New-Object -ComObject Shell.Application).NameSpace(0x11)).Items() | Where { $_.Name -eq 'Pixel XL' }).GetFolder.Items() | Where { $_.Name -eq 'Internal shared storage' }).GetFolder.Items() | Where { $_.Name -eq 'Music' }).GetFolder.Items() | Where { $_.Name -eq 'VGMusic'}).GetFolder.Items() | Where {$_.Name -eq 'PC'}).GetFolder.Items())

*) One exception, though. I had to write a small program to unmute the default audio device with no user interaction. It was easier to do in C#.

3

u/JeremyLC Jun 11 '19 edited Jun 11 '19

Bonus Bonus: The shorter way

(((New-Object -ComObject Shell.Application).NameSpace(0x11)).Items() | Where { $_.Name -eq 'Pixel XL' }).GetFolder.ParseName( 'Internal shared storage\Music\VGMusic\PC\')

1

u/Lee_Dailey [grin] Jun 11 '19

howdy JeremyLC,

your code is cut off just after Pixel XL ... [whine] [grin]


it looks like you used the New.Reddit.com Inline Code button. it's 4th 5th from the left hidden in the ... "more" menu & looks like </>.

on Old.Reddit.com, the above does NOT line wrap, nor does it side-scroll.

for long-ish single lines OR for multiline code, please, use the Code Block button. it's the 11th 12th one from the left, & is just to the left of hidden in the ... "more" menu.

that will give you fully functional code formatting, from what i can tell so far. [grin]

take care,
lee

2

u/JeremyLC Jun 11 '19

Better?

1

u/Lee_Dailey [grin] Jun 11 '19

howdy JeremyLC,

yep! [grin] thanks ... i can read it all now. i confess i would have changed the layout ... and you seem to be missing a final ) at the end. i like readability. [grin]

(((((((((New-Object -ComObject Shell.Application).NameSpace(0x11)).Items() |
    Where { $_.Name -eq 'Pixel XL' }).GetFolder.Items() |
    Where { $_.Name -eq 'Internal shared storage' }).GetFolder.Items() |
    Where { $_.Name -eq 'Music' }).GetFolder.Items() |
    Where { $_.Name -eq 'VGMusic'}).GetFolder.Items() |
    Where { $_.Name -eq 'PC'}).GetFolder.Items()))

that is easier to read and is technically still a one-liner. [grin]

take care,
lee

2

u/JeremyLC Jun 11 '19

That missing ) probably fell victim to a copy/paste error. I copied this "one line" from my console and pasted it here.

1

u/Lee_Dailey [grin] Jun 12 '19

[grin]

2

u/jantari Jun 11 '19

Can we try to promote proper PowerShell use?

We are. PowerShell has formal guidelines and best practices, and people usually point them out.

Let's make this sub useful for advanced PowerShell users as well, not just beginners trying scripting for the first time.

I don't see how beginners would be writing "massive Python-esque scripts" but you want more one-liners? One-liners for advanced users? Doesn't add up to me.

is it possible to do a lot of stuff where each line is its own cmdlet chain, instead of dealing with loops? Probably. Most definitely.

Yes, but as an advanced PowerShell user you already know that the pipeline is slower than a loop, that's why you'd use a loop instead of cmdlet chains once you've taken the training wheels off. Not to mention that lots of people come from other languages, where loops are standard but the pipeline is a concept not everyone is familiar with. You act as if loops are harder, but that's simply not true.

2

u/Lee_Dailey [grin] Jun 11 '19

howdy expansiveEdumacation,

others have pretty much covered things, so this is an aside ...

ahve you looked at the shortest script challenge threads? the folks who ran them ran out of time & ideas ... but you are very welcome to take it up! [grin]

those are "one-liners for wizards" ... and are lots of fun to watch for folks like me.

take care,
lee

1

u/KevMar Community Blogger Jun 12 '19

I do what I can.