So what are some tips and tricks for creating scripts?
So what's the first tip?
Well, the first one is to comment the code.
Trust me, having written lots of PowerShell scripts over the years,
sometimes you come back to it, and you spend the first hour trying to
figure out what you wrote because there was no comments.
If you simply write comments at the top and comments in the code,
anybody will be able to go through quickly and see what the code does.
Second is to use unique variables as names.
And just be aware, once you do this and, you know, you end up
creating a variable, and you end up renaming the variable or
creating it with the same name further down,
and you spend almost a day trying to debug why the values keep
changing, you'll soon realize why you should create unique variable
names. And strongly typed them, if needed,
so you can constrain the input that comes in there.
Name them something that makes sense too. Don't
call them variable1, 2, 3, and 4.
Call them what they're supposed to be.
If the variable is to contain JSON and it's from server1, call it
server1json so you know exactly what that would be.
Then, of course,
you can use what's called start/stop transcript. Now we haven't talked about
this one, but this is a way for you to, when you execute a piece of
PowerShell, if you start the transcript and stop it,
you'll have a output of all the logical steps that took place.
Use try/catch.
It's just an easy way to capture any of the thrown
exceptions and errors and be able to control the flow that
you're running inside those functions.
When you call a function, try/catch it in the function try/catch.
Also, use conditional logic, if loops, if/else, switch statements,
whatever it would be. Use conditional logic where possible to be
able to validate the path that it should take.
And then, of course, lastly use loops to iterate the content.
So if you have data coming in, look at how you loop, loop the values, and update things as you go ahead.