How to learn better formatting

Occasional Visitor

I just finished writing my first larger PowerShell script to automate a process.  For a beginner, I was pretty impressed at myself in what I did ..... until .... I went back to fix a minor issue with file naming.  I got that fixed, but in troubleshooting I realize my script is a mess, it works, but following my logic is all over the place.  how do you learn a better logical format to use when writing?  Are their people you can send a script to and ask "how would you have done this"?  I used here and google to figure out how to do the logic on HOW to do it.  But how do you find out the "you could have done it better by..." or "it would be easier to follow if you'd ..."  type stuff?

1 Reply
My personal experience is that it grows over time, it's a matter of experience. There are a few things that I always try to do to make things more readable:
- Don't use short names or aliases like select (select-object) or gci (Get-childitem. Always use the real name
- Use # (Comments) to explain (Shortly) what that specific section does
- Use Visual Studio code and the Right-Click / Format Document option so that it aligns everything nicely making it more readable
- When using Visual Studio Code, store your scripts in Github in a private repository. Versioning/roll-back etc can help a lot!
- Don't use commands which are longer then your screen, use splatting ( for passing the parameters
- If you have to use .exe's in your scripts, use 7zip.exe instead of 7zip for example to show that you're calling a executable instead of a cmdlet
- Use error handling, try/catch of if/else
- Use parallel in foreach statements if possible to speed up long running scripts
- Make sure that you're script runs in 5.1 and 7.x, if only in 7.x make sure you specify that
- Keep your modules up-to-date using update-module
- Keep your help up-to-date using update-help
- Be consistant in how you decclare variables and what names you use
- Don't copy/paste examples and just run them but determine for yourself what is happening and use it in your own scripts

My 2 cents :D