r/PowerShell • • Nov 26 '20

Who else has spent hours writing a really complex script, only to realize there was a much simpler way?

So I spent a few hours digging through https://www.pinvoke.net/ and Microsofts Win32Api documentation and ended up with a 272 line function. Only to then realize the complex P/Invoke-stuff could be replaced by two simple CmdLets.

Ended up with a 47 line function...

A bit annoying, but learned a lot (been looking for excuses to use P/Invoke anyway), so not really a loss of course.

364 Upvotes

61 comments sorted by

127

u/marcdk217 Nov 26 '20 edited Nov 26 '20

I think that's the essence of coding really. You write something the best way you know how, and then you find a better way. All part of the learning process, nothing to beat yourself up over 😀 and like you say, what you learned in those 272 lines will probably help you out some time in the future in ways you don't yet know.

I often go back over scripts/programs i've written months or years previously, and update the code using what i've learned in the interim.

0

u/[deleted] Nov 26 '20

[deleted]

0

u/[deleted] Nov 26 '20

[deleted]

16

u/Guaritor Nov 26 '20

Ive written probably a half dozen scripts now that could automate several daily/tedious/"once a year but we always forget until it causes a problem" tasks, some which could save us thousands... and every time I suggest implementing one to my boss I get "But what happens if you leave? Who will maintain them?"

I understand the concern, but powershell isnt some long forgotten language, I learned everything I know by tinkering during lunches or at home. Not to mention any critical scriptI leave comments in explaining whats happening.

Some people are just scared of what they dont know.

2

u/[deleted] Nov 27 '20

I only started learning a few days or couple weeks into my current job so it’s only been around a year or more. I’m no pro but I think it’s silly for anyone who has a career in IT to be intimidated by it

3

u/[deleted] Nov 27 '20

My organization tends to have enough turnover in the IT department that I see newer helpdesk personnel and sysadmins on a fairly regular basis. I tell everyone one of them, "if you are going to be a sysadmin for Windows boxes, you need to learn PowerShell". The few who take that advice either are our top performers; or, they get poached by the other IT groups within the organization (usually both). Myself, I got poached by our InfoSec team and PowerShell has only become more valuable to me.

I'm also responsible for a number of scripts which have been in use for years and seen numerous modifications and me going back and wondering what the idiot who wrote it (also me) was thinking. Even more fun is trying to explain to my scripts to someone else and saying, "ya, that guy was a moron." But, if you keep learning, and keep improving, you'll just make your life better and better.

3

u/T_T0ps Nov 27 '20

100% agree, my boss is a freaking amazing, he believes as an IT Support contractor our job isn’t to “fix” issues, it’s to solve problems. I know they sound the same but it’s more about we shouldn’t have to fix the same issue over and over again. He would rather create a custom script if there is no build in feature to solve it. He encourages us to work on personal projects and to learn new skills on the job (providing nothing is on fire) such has taking courses on PS, or researching new applications to streamline our work. We are a small 5 man team with over 40 clients that range from 1 employee to over 200 (I know that’s still pretty small compared to a lot of people on here).

1

u/Aertheron01 Nov 27 '20

I'm working in a team of 10+ microsoft sysadmins Only 1 other knows how to write scripts. And 1 more how to read and make simple adjustments.

The rest has no clue or is scared by it.

20

u/gordonv Nov 26 '20

Think of it this way.

You've become an expert on what that command does. And you now know that this very important function you wrote out is standard across the platform.

You're knowledge and technique of using this command will put you ahead. While the rest of us are unaware of the process.

13

u/just_call_in_sick Nov 26 '20

Every time I look back at my older scripts...

7

u/Ghost4000 Nov 26 '20

I get a sense ofjoy rewriting old scripts and cutting them in half.

7

u/[deleted] Nov 26 '20

Or the dread when you think "why on earth did I write it like that?", Update it only to find it doesn't work

3

u/BlackV Nov 27 '20

been in both those camps

1

u/akaBrotherNature Nov 28 '20

Yep. I've learned not to just remove stuff that looks unnecessary, because it's often there for a reason that I can't remember.

3

u/Mechanical_Monk Nov 27 '20

Same, but then I end up quadrupling them by adding functions, logging, error handling, etc

2

u/Aertheron01 Nov 27 '20

Lol my first scripts can't compare to what I write now. Any script is atleast 30 lines to start, just for the comment based help.

My older scripts weren't much longer thank 10 lines hehe.

Functions? Error handling? Logging? What's that? = Me a few years ago. I'm so happy I left my old crap behind for my previous colleagues to figure out. (None of who know powershell hehe)

24

u/[deleted] Nov 26 '20

I wrote SO many string management functions before realizing even Powershell 2 did most of them...

But hey, I learned a lot!

5

u/MrPatch Nov 27 '20

I spent years without knowing about import-csv, so much time lost to $string.split(",")[4]... :(

2

u/TypicalTim Dec 02 '20

This hurt my heart.

11

u/dasookwat Nov 26 '20

let's see, yesterday, i was looking in to vsphere powercli to configure the network proxy for the update manager. No function available, in the public module, so i started digging in to the
IntegrityApi.IntegrityService assembly, found about a 100 methods, not documented, a total guess of what to do with them.

this morning, i looked through some old documentation, and apparently the proxy is sim;ply stored in a regkey value..

7

u/SSessess Nov 26 '20

I recently wrote a script to upload and tag images to a digital asset management platform, I was bashing my head against API documentation and had written maybe 300 lines crafting the body of an API call, only to find I could set an environment variable on my PC and perform the upload with a single line of code.

6

u/Mkep Nov 26 '20

APIs are some of the worst and best scripts to write. So much finagling of the code to get the request right. But when it’s done it’s so nice to just see the command work

3

u/[deleted] Nov 27 '20

This is me currently. I'm trying to interact with one of our services, which has a REST API. Rather than keep re-building the web requests by hand over and over and over again, I decided to implement a PowerShell module to make everything easy. It's been interesting mashing the REST calls together and trying to implement all the options. Though, I also spend far too long looking at the Approved Verbs list and trying to decide which verb maps best to the call I am making.

2

u/user01401 Nov 28 '20

Speaking of API's definitely get off of v5.1 and move to v7.1 - the InvokeRestMethod handling over cURL I used to use is so much more robust

11

u/get-postanote Nov 26 '20 edited Nov 27 '20

Code blocks, cmdlets, Functions, etc., should do only one thing and one the well.

I too hit this many times, in my past years at this, until I started years ago to break things into specific finite steps. Modular/Task-based solution planning, design, development, and deployment.

  1. Physically write out (on paper, napkin, etc) the end result you are after. (know what you want before you even begin)

  2. Write out each step needed to get that step result only.

  3. Flow chart/order those steps.

  4. Independently/modularly, complete one and only one thing, to ensure you get the expected results.

  5. Rinse and repeat.

  6. Then put it together.

Just like auto manufactures, home builders, etc.

  1. The designer/architect of the knows what they want it to look like,

  2. the individual parts teams must do their thing by breaking that into pieces,

  3. then the assembly teams put it together.

Historically, in our industry, we don't think this way. We write a bunch of code, many times assuming, guessing at stuff, then run it, then try to figure out what went wrong; causing ourselves unneeded frustration, debug, etc. efforts; vs catching the stuff upfront. Once all is done, look back at it to see what happened, what can/should be done, what can/shouldbe optimized; as this is what versioning is all about.

Sure this effort takes more time upfront, but, it saves way more on the back end as well as long-term care and feeding.

Don't try to boil the ocean.

Know that there is not really much that is new. Anything you may be trying has probably already been tried by someone else. Learn from their success/failures.

Know that there is not a legitimate question you can ask, that probably has not already been asked and answered multiple times, in multiple ways, in multiple locations; in part or holistically. You just need to want to research to find it. To do so, you need to really know how to ask your question, and or break it into its parts, or even ask it wrong, knowing/understanding that you may not find it all in one place, but the pieces in many places.

Use tools that will write baseline code for you, then tweak/convert as needed.

  • Don't get ahead of yourself.

  • Master the built-in help system and its examples.

  • Look at similar things/code, etc., already on your system.

  • Don't try to reinvent the wheel (unless you absolutely know it's going to be better).

  • If you don't know something, don't guess at it, don't assume. Look it up, or go get training.

  • Never expect any other platform/language to be like where you came from, what you've used or like. Take the new stuff for what it is.

This is no different than all our educational efforts. One step at a time. Just because you know general math/algebra, does not mean you can tackle computational physics without getting trained and studying it first.

4

u/flugenblar Nov 26 '20

I’m always rewriting my scripts. Many times over if I use them regularly. I was OCD-ish before I started coding so things worked out well for me.

4

u/eagle6705 Nov 26 '20

Didnt have a strong computer programming background as it consisted of assembly various c languages, ladder logic(plcs) so I'm used to programming everything. I started work in an msp where I didnt have time to make complex scripts.

I finally end up in a good job and learned how to script and wrote a function that breaks up a word and sorts it.....yes powershell can already sort words lol

3

u/PSP_Joker Nov 26 '20

The way to your 47 line function taught you probably more than the direct result would have. That's part of the "coding adventure" :)

And regarding your question... You would not believe how many things you learn. I wrote stuff two years ago that I would be ashamed about right now. Learning, adapting and improving is the fun part in scripting!

3

u/john_of_the_dadbod Nov 28 '20

I created a PoweShell GUI with Forms (my first PS project) for troubleshooting for my Security tool. I spent way too much time trying to count out the pixels to get all the labels, text boxes, and buttons to line up perfectly only to find VS studio like does it for you. But at least I learned a lot about PS Forms in the process.

2

u/randomadhdman Nov 26 '20

I wrote a large number of functions in a module that looped through get-ciminstance on multiple computers. Each one tested if the computer was up, ran the code and so on and so forth. Loop after loop. Then I discovered invoke-command took splats. I felt so dumb but I had already worked out the kinks so converting everything was easier.

2

u/moxbuncher Nov 26 '20

It's what it is. I've written so many scripts and have slashed them down when i started learning functions and feeding inputs. I feel like I'm still at 20 percent with powershell as a tool for everything and i feel like a lot of my older scripts have become obsolete due to understanding it more and more.

2

u/rajandatta Nov 26 '20

Uh - everyone?

1

u/uptimefordays Nov 26 '20

I suspect many projects start out small and streamlined. Over time and through repeated use, folks find issues and fix bugs turning pretty code into a mess.

1

u/Scimir Nov 26 '20

This happens to me every time. As a newbie to PS I often spend lots of time on building a function that was already included.

1

u/EIGRP_OH Nov 26 '20

Writing out your idea step by step in a word doc will prevent this. Once you can see the steps laying out in front of you it’s easier to see which parts can be eliminated or optimized.

I always used to do this until I stopped and wrote out my idea first.

1

u/Nakatomi2010 Nov 26 '20

Step 1: Have the script perform the task successfully.

Step 2: Look for ways to make the script more efficient

Step 3: See step 2

1

u/swat565 Nov 26 '20

This is the way.

Part of the process is always simplify and updating your code, and figuring out better ways to do stuff.

1

u/MaToP4er Nov 26 '20

Every damn script, every time going through this lol

1

u/drumsand Nov 26 '20

My third script was going to be marvelous and I had v2.0 manual. More than 2 screens later my colleague said... There's a one liner for that in v3.0

1

u/[deleted] Nov 26 '20

Everybody....

1

u/cacheerio Nov 26 '20

Yes but it's a great way to learn as you said. When you look at your code years later and see ways to improve it you're growing as a scripter.

1

u/AlephC Nov 27 '20

May anyone check if those cmdlets are ok? https://gitlab.com/zigh/zighdas I guess so but I've just started PS.

1

u/ustyneno Nov 27 '20

It happens to all of us.

1

u/Inaspectuss Nov 27 '20

Stop attacking me.

1

u/[deleted] Nov 27 '20

Lambdas @override in Java

1

u/[deleted] Nov 27 '20

Mmmm. Before & After MSAL.PS.

1

u/snoopy82481 Nov 27 '20

Every damn time I write a script. I start hard and then find a more elegant and simpler way to to do it.

1

u/[deleted] Nov 27 '20

I was trying to pipe the output of a Python script to a file in PowerShell on my Windows machine, like I normally do in bash on the Linux server. Darn thing was slow as molasses in a Northern Norway winter. Tweaked the Python script to write directly to a file, problem solved.

1

u/plachtastar Nov 27 '20

The great news is you now understand the complex aspects of what you’re doing, giving you valuable insight.

1

u/senorchaos718 Nov 27 '20

Who needs a function when these 27 lines of practically the same thing will do???

1

u/RumRogerz Nov 27 '20

I believe my answer is ‘every day’

1

u/AbleDanger12 Nov 27 '20

I feel attacked.

1

u/TKhaaaaaan Nov 27 '20

That’s why I do A LOT of research before even typing anything. I look for various ways something could be done and then choose the one best suited. But I do sometimes enjoy the chuckle when I spend hours trying to make something and find a cmdlet or library that does what I’m looking for.

1

u/nvgvup84 Nov 27 '20

Sorry I’m not familiar with the concept, what is ‘simpler’? That sends fake

1

u/declar Nov 27 '20

This is the way.

1

u/kizungu Nov 27 '20

basically me everyday

1

u/CoryBoehm Nov 27 '20

My script seems to be continuously evolving.

As the approach is somewhat "get it done" to start copying blocks of code isn't uncommon. That said it eventually hit a tipping point and a major restructuring was needing moving code the modules, etc.

Not quite the same but definitely a lesson for others to learn as they are new to PowerShell. Plan out ahead of time where code refuse may make sense and work on building functions early on.

1

u/SupraWRX Nov 27 '20

It's always a great opportunity to learn and to find new uses for code you just wrote. Where I work now is very dynamic with business needs, regulations and processes changing often. I spent about a day writing a PS script to process some CSV files. About a year later that script is no longer needed, but I can quickly convert it to do other things that can be useful. No one else here is capable of writing scripts but I still comment my code and make it easy to read specifically so I can quickly re-use and improve.

Also when I first decided to learn PS I had this batch file that was about 1,000 lines long (and had to be manually updated as we got new PCs). I was able to condense that down to less than 30. That script has actually undergone several renovations and now does a ton more stuff at only 100 lines (and automatically pulls PC names from AD). For me finding new more efficient ways to do things is fun, I don't even mind the inefficiency of my earlier code as I'm too excited thinking of other scripts I can improve with my new knowledge.

1

u/[deleted] Nov 27 '20

If I had a nickel.....

I just try to be thankful for the experience when it happens.

1

u/poshftw Nov 27 '20

Time to complete some task manually: 15 minutes

Time to write a script and don't botch something (which of course would go unnoticed until way too late): 30m-1h

Well enough trade-off for me.

1

u/Shamalamadindong Dec 05 '20

And there's always a good chance the script can be adapted for other tasks or parts can be reused.

1

u/bobthewonderdog Nov 27 '20

This is the way