Chapter 20. Adding logic and loops

 

Up to this point, I don’t consider anything that we’ve done so far to be “scripting.” It depends on your definition of the word, of course, but to me scripting is a kind of programming, with formal constructs that define logic, repetition, and so forth. You can do a lot in PowerShell without that stuff. But the time will come when you will need to write a script that can make logical decisions, and you’ll start to move beyond running commands and moving into simple scripts.

The goal in this chapter is to let you experience some of PowerShell’s major scripting constructs for logic and repetition, so that you’ll be prepared to use these elements when the time comes.

20.1. Automating complex, multi-step processes

I typically find a need for these constructs when I’m automating more complex, multistep processes. For example, consider a script that provisions a new user: you need to create an Active Directory account, add the user to some groups, create a mailbox, create a home directory on a file server, and so on. Those processes often involve questions, with branching logic: Should the user belong to such-and-such a domain user group? Should they have access to certain files? Each question leads to a slightly different course of action. In some cases, certain operations may have to be done over and over, such as adding a user to several groups, or perhaps granting them permissions over several folders or files.

20.2. Now we’re “scripting”

20.3. The If construct

20.4. The Switch construct

20.5. The For construct

20.6. The ForEach construct

20.7. Why scripting isn’t always necessary

20.8. Lab