r/PowerShell • u/adbertram • Jul 16 '20
Want to Write Beautiful PowerShell Code? Here's How.
Hey guys, I just wrote a shiny new blog post you may enjoy.
"Want to Write Beautiful PowerShell Code? Here's How."
Summary: Learn how to write beautiful PowerShell codes with these step by step tutorial. Learn recognizing patterns and standardization to build entire solution.
25
u/IveGnocchit Jul 16 '20
Thanks Adam, love your work.
I wish that more people cared about this type of stuff š
20
u/suddenarborealstop Jul 16 '20
Oh people definitely care, but they are down voted here when they reply with ādeveloperā answers. Classes are highly under-utilised. Pattern matching also. Thatās why Adamās writing is good. He doesnāt care. He writes and says āhereās some shit you should be doing if you ever want to work with meā. Same with don jones and a few others.
7
u/xophh Jul 16 '20
Quality code is so important when you're on a team. If you're just a developer, you can get away with doing whatever you want, but you better pray nobody inherits your code, and you better not have a desire to become an engineer.
I love the team I work on because code reviews are not only about whether the code actually works and all the usual code review stuff passes, but also because we will call each other out when the code does not feel good or when it smells. At the end of the day, I don't hate everybody I work with after spending time working with their code.
7
u/acidproton Jul 16 '20
I argue against doing "whatever you want," even if you're a lone developer. Because, some six months later you will inherit your own code and sometimes have to relearn why you did "that"? Or worse, wonder who the idiot was that did "it that way," to learn you were the idiot.
As I read somewhere, assume the next person inheriting your code is a psychopath that knows where you live.
2
u/xophh Jul 16 '20
Agreed. I guess I meant do whatever you want (DISCLAIMER: DON'T REALLY BECAUSE YOU'LL HATE YOURSELF). But at least in that case you won't get fired for being incompetent, unless you really messed yourself up that bad. Lol
-3
u/guy1195 Jul 16 '20
I actually just downvoted due to all the adverts on his website.
23
u/adbertram Jul 16 '20
An unfortunate requirement for keeping 2-3, long form, high quality blog posts with editing going by multiple authors.
18
u/suddenarborealstop Jul 16 '20
The ads are a bummer but probably pays for hosting. Donāt reckon heās buying a super yatcht with the ad profits
18
u/adbertram Jul 16 '20 edited Jul 16 '20
You are correct. They actually pay for hosting and to pay guest authors.
6
2
u/Yevrag35 Jul 17 '20 edited Jul 17 '20
I had someone try to rationalize to me the reason that they don't use parameters in functions (in FUNCTIONS for %*@# sake) and instead use "global" variables is because it takes too much time to write.....
And they wonder why I can't debug their code.
Step 1: Download VSCode
Step 2: Learn to use Snippets (Here are mine - they help)
2
3
u/MonkeyNin Jul 17 '20
Depending on the version of powershell you can use
[typename]::new()instead ofNew-Type
19
u/itasteawesome Jul 16 '20
This abstraction stuff is timely, I just had to update a set of scripts written by my predecessor at work to utilize some new API functions. I had been avoiding touching this thing because it was 6k lines. Extremely well documented internally, but basically for each scenario he just popped in the full json to make it happen. So if we wanted something done to a prod environment here's 30 lines of json for prod and next will be the full 30 lines of json for dev. Repeated over and over to handle all our scenarios. All the REST calls with the API itself had been given functions but creating the payloads appears to have been a straight copy paste affair. I picked out the parts of the script that are actually necessary to change for our use case, wrapped everything up in some loops and switches and consolidated it down to 1200 lines. Feed it a list of conditions you want built and the script parses all the info we needed from the list, builds the required json from a few templates, and pumps it through their API. If I need to change something later on all the actionable code is in one place and I don't have 20 sections I'd need to find/replace my change into.
I really like the guy I replaced, knew him outside of this job, but he has left behind a legacy of so many crazy long and repetitive scripts that are such a pain to update.
20
u/Flyboy Jul 16 '20
I had a long time member of my team who was very smart and enjoyed coding. Had a CS degree from the 80s I think but worked as a sysadmin. A lot of our automated processes ran on his code, whether it was batch, VB, Perl, and I think he even dabbled in C#. When I joined the team I encouraged him to look at Powershell and he went down the road of converting most of "his" scripts to PS.
I considered him a friend, but his code was actually kinda terrible. Not that it didn't work - it did, usually - but it followed none of the practices Adam discusses here. No functions, no parameters, entire blocks of code copied & pasted into multiple scripts, hardcoded paths...
But because he took 'ownership' of these processes nobody held him accountable for years and there was no incentive for him to improve his code. That's a management issue for us, I'm aware, but my point is that good code is a gift to your team and it ultimately benefits the organization.
The subject of my story has retired now and I and another new person have the task of untying the knots that he left us. We discovered a problem in a provisioning script, a block copy/pasted from another, that was the root cause of the CEO temporarily losing his security access. Big screw up. We fixed it but the incident showed us just how bad the situation is.
I think we who work in IT ops often don't see a need to "beautify" our scripts because we have a "get it done" mindset. If it works, etc. That's good enough for management. This is also why there's stagnation and resistance to DevOps as a cultural change. My team is a long way from maturity on that journey but I feel that taking pride in creating high quality reusable and robust Powershell is a good place to start. It's my hope that embracing this grassroots shared value of code craftsmanship will take us further down that road, leading to us adopting source control, deploying infrastructure and configuration as code, and adopting other dev practices. None of this depends on management, we will do it ourselves. Maybe I'm too optimistic but it's my intention.
6
Jul 16 '20
I've been guilty of this in the past. Implement a quick fix solution or quick ugly POC and part of it makes it prod.
5
u/jsiii2010 Jul 16 '20 edited Jul 16 '20
The creator of Erlang agrees with you. The last step is to make it beautiful.
"The Mess We're In" by Joe Armstrong https://www.youtube.com/watch?v=lKXe3HUG2l4
See also
The Forgotten Art of Structured Programming - Kevlin Henney [C++ on Sea 2019] https://www.youtube.com/watch?v=SFv8Wm2HdNM He basically talks about being able to see the structure from the indenting, without any surprising movements around the code. Make the code "reasonable", in that you can reason your way through it.
To me making it beautiful is part of the fun, time permitting.
4
4
u/smalls1652 Jul 16 '20
The more changes you must make to your PowerShell code, the more youāre doing it wrong. You should focus on making code resilient across many different contexts and use cases. The best way to do that is through parameters.
[...]
Why does this context matter? Because when you move to that other team, you don't have to change any code at all. You simply change a parameter value. You're separating the "doing" from the "invoking" making code flexible and portable.
This. So much this. Any script I make, I try to imagine the multiple use cases I may have with that script. Even for Azure Automation Runbooks, I define the parameters and, usually, apply default values to those parameters. That way I donāt have multiple different variations of a script/runbook. Not to mention, youāve now got a tool in your toolbox that can with you anywhere. That means it could be shared publicly or to another job.
One such script I wrote here recently, is a bit tailor made to my work environment; however, Iāve tooled it in a way that it gives me flexibility in how itās used. For example I need a Windows Server VM spun up in Azure, but I donāt want to constantly go through the process of running multiple different commands from the Az modules. The server needs to be in a particular subnet for a virtual network and applied a specific DSC config, so I just get the returned output from the respective commands to get that information and supply it to the respective parameter for my script. Itās dynamic in nature for future deployments!
3
3
1
2
u/yourenotwurvy Jul 16 '20
Nice post, abstraction is a silly term but conceptually itās a good read for anyone keen to deliver agile code & to avoid duplication.
2
u/elkBBQ Jul 17 '20
Want to write beautiful code that's a joy to work with? Start with adding parameters and help to it. Code isn't very useful if you can't determine what it does through the built in help system.
2
2
u/Cladex Jul 16 '20
Awesome work Adam, I have found your website the best of breaking down scripts and explaining the code. Really helped me to learn!
Would be awesome if you could write a guide on commenting/annotations best practices for scripts.
2
u/MisterPhamtastic Jul 16 '20
Commenting to save forever thank you sir
7
u/portablemustard Jul 16 '20
Just an FYI. I see nothing wrong with commenting to remember a post but in case you're curious reddit has a save option too. Even on mobile.
6
u/MisterPhamtastic Jul 16 '20
I like it when people comment on my comments because the only time people talk to me at work is when something breaks
3
u/Lurkin_N_Twurkin Jul 16 '20
If you are on android reddit app, it is a little "ribbon" icon at the top right.
1
u/eltiolukee Jul 17 '20
welp, i sure wish i had seen this a couple of years ago.
Don't wait up for me, i'll be rewriting some stuff
1
1
Jul 17 '20
Hi Everyone
How to do SQL Automation deployment using power shell codes using JSON file ?
How to get a error code when we get error while we run the power shell through the SMTP server mail with HTML or text message?
How can we see that when we run the JSON configuration file it has successed or failed using power shell?
Will you please help me out in this.
1
u/AutoModerator Jul 17 '20
Sorry, your submission has been automatically removed.
Accounts must be at least 1 day old, which prevents the sub from filling up with bot spam.
Try posting again tomorrow or message the mods to approve your post.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
1
u/darudeboysandstorm Jul 17 '20
Awesome article, I am very much so a novice only using power shell to do discovery/admin work and really have been trying to develop more. This article really helped me do some critical thinking of my own and o loved it and learned a lot.
1
u/LockQuirky Aug 12 '20
I need this, Thanks for sharing. As a newbie in PS, I need to keep these things in mind as I learn PS.
1
u/Zendist Aug 16 '20
Get-Verb can be used to figure out which PS-acknowledged verbs you can use. I also use the output sometimes for command-name inspiration.
1
1
1
u/Celadin Jul 16 '20
Yes! So good. Sharing this in as many places as possible. I've been subtly encouraging teammates to follow some of these general principals but without really having concrete terms its been a bit tough to convey. Thanks for laying it all out so clearly! Gonna be a big help especially for some of 'em who are just getting started. Solid foundations ftw.
-3
Jul 16 '20
This is gonna be unpopular opinion, but the most beautiful PS code is actually F#.
1
u/jsiii2010 Jul 16 '20
Functional programming in powershell: https://www.reddit.com/r/PowerShell/comments/bxrhnv/functional_programming_in_powershell/
5
u/ISeeTheFnords Jul 16 '20
It's a nice idea. I suspect he runs into some namespace problems with his example when both HyperV and VMWare use "Start-VM" as their cmdlet.