Chapter 4. Windows PowerShell Functions, Parameters, Sourcing, Scopes, and User Profiles

In any programming language, code reusability is both common and important. It increases productivity and decreases the need to write redundant code blocks. Another important basic functionality in any programming language is the scope of variables and functions.

This chapter focuses on the reusability of PowerShell scripting. You will learn how to reuse code blocks through functions, sourcing files, and user profiles. You will also be introduced to variable scopes and function scopes. Finally, this chapter also covers transcripts.

Functions

Functions are modules or blocks of code that can be reused repeatedly in programming by just calling the block of code by name. Creating functions reduces the writing of redundant code and increases productivity. Functions can be written inside the main script or can be sourced in from a file.

The following code creates a simple function that displays a welcome message to the user:

function Hello
{
write-host "Welcome to PowerSQL"
}

You can call the function by just typing "Hello," as shown in Figure 4-1. This function has no return value or parameters.

Figure 4-1

Figure 4.1. Figure 4-1

Arguments in Functions

Functions accept arguments or parameters if you define them in the function. There are two ways to define arguments. One is using the argument variable args. This is the ...

Get Microsoft® SQL Server® 2008 Administration with Windows PowerShell™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.