PowerShell - am I doing it wrong?

Hey all,

I find I am using PowerShell very heavily at the moment, converting all our old scripts to PowerShell and I love the flexibility and power the language provides, however my scripts are not written in the cmdlet style, they are written to get the job in question done, much like a batch file or vbscript would be written, is this wrong? Should I be aiming to write everything in the cmdlet style?

Currently reading ‘Learn Powershell Scripting in a Month of Lunches’ and it got me thinking…

Thanks for any guidance you can provide.

Yes. You should.

Learn PowerShell Scripting in a Month of Lunches will be the way to start that :).

I would first start trying to generalise and compartmentalise portions of your scripts. There are often things we do that can be reused elsewhere with small modifications. Start there, put that code into its own function, and reuse that instead of coding the same thing multiple times.

Then, look at it, and ask yourself: “Can I generalise this further to make it useful in more situations by adding a few parameters that can be modified later?”

Then just get heavy into validating your parameters, and if you want you can look at dynamic parameters (though frankly I avoid those where possible and haven’t found many good use cases for them as yet). At that point, you’re pretty close to what you’d call a cmdlet.

Check out Get-Help about_Advanced_Parameters and see what you can do with them.

After that, it’s a matter of looking critically about what output your functions have, and how you can make it more useful.

At that point, you should start considering turning groups of your functions into a module. Some of KevMar’s blog posts are quite good on that topic. :slight_smile:

Thanks very much for the responses - I guess I need to start looking at the scripts I am writing and turning them into something re-usable - like you say, first put them into functions and then move on from there instead of literally just writing a script as a would a batch file or something.