Solved

powershell script structure

Posted on 2011-09-22
1
743 Views
Last Modified: 2012-05-12
Are there any recommended "best practices" for structuring powershell scripts to avoid very lengthy, spaghetti-like code.
0
Comment
Question by:AlStoughton
1 Comment
 
LVL 16

Accepted Solution

by:
Dale Harris earned 500 total points
ID: 36581712
Create functions whenever possible.  You'll find that functions help clean up your code into blocks of manageable data.

Stick with a structure that is easy to read.  One liners are cool, but you should save those really cool one liners for console stuff.  You should always space out your code to help other people see it clearly for what it does.

Comment before huge blocks of code.  Sometimes the comments you see are every other line like #I'm about to write to the host.  That's a little too much I think and creates more clutter.

Define variables at the top of your script.  That way if anyone comes in after you, they can just modify one section and be able to use your script.

Always code like you think someone else will have to read it and you'll have to explain it to them with comments, not talking with them personally.

And that's not just so you can have other people look at your code.  Have you ever tried looking at some abstract script you wrote while on a caffeine high during the wee hours of a night 6 months after you wrote it?  Sometimes you can confuse yourself, so always code clearly and define anything murky that might cause someone to stumble or ask questions.

That's all I think think of right now.  Have you already checked out the articles in EE for Powershell?  There's some good ones in there.

HTH,

Dale Harris
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
A procedure for exporting installed hotfix details of remote computers using powershell
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now