Book Image

Windows Server 2012 Automation with PowerShell Cookbook

By : EDRICK GOAD
Book Image

Windows Server 2012 Automation with PowerShell Cookbook

By: EDRICK GOAD

Overview of this book

Automating server tasks allows administrators to repeatedly perform the same, or similar, tasks over and over again. With PowerShell scripts, you can automate server tasks and reduce manual input, allowing you to focus on more important tasks. Windows Server 2012 Automation with PowerShell Cookbook will show several ways for a Windows administrator to automate and streamline his/her job. Learn how to automate server tasks to ease your day-to-day operations, generate performance and configuration reports, and troubleshoot and resolve critical problems. Windows Server 2012 Automation with PowerShell Cookbook will introduce you to the advantages of using Windows Server 2012 and PowerShell. Each recipe is a building block that can easily be combined to provide larger and more useful scripts to automate your systems. The recipes are packed with examples and real world experience to make the job of managing and administrating Windows servers easier. The book begins with automation of common Windows Networking components such as AD, DHCP, DNS, and PKI, managing Hyper-V, and backing up the server environment. By the end of the book you will be able to use PowerShell scripts to automate tasks such as performance monitoring, reporting, analyzing the environment to match best practices, and troubleshooting.
Table of Contents (19 chapters)
Windows Server 2012 Automation with PowerShell Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating and using functions


Functions could be considered one of the cornerstones of PowerShell scripting. Functions allow for individual commands or groups of commands and variables to be packaged into a single unit. These units are reusable and can then be accessed similar to native commands and Cmdlets, and are used to perform larger and more specific tasks.

Unlike Cmdlets, which are precompiled, functions are interpreted at runtime. This increases the runtime by a small amount (due to the code being interpreted by the runtime when executed), but its performance impact is often outweighed by the flexibility that the scripted language provides. Because of this, functions can be created without any special tools, then debugged, and modified as needed.

Let's say we are preparing for Christmas. We have made a large list of things to complete before the Christmas morning—wrap the presents, decorate the tree, bake cookies, and so on. Now that we have our list, we need to know how long we have until Christmas morning. In this way, we can prioritize the different tasks and know which ones can wait until later.

We could use something simple like a calendar, but being PowerShell experts, we have decided to use PowerShell to tell us how many days there are until Christmas.

How to do it...

Carry out the following steps:

  1. We start by identifying the necessary PowerShell commands to determine the number of days until Christmas.

  2. Next, we combine the commands into a function:

    Function Get-DaysTilChristmas
    {
    <#
       .Synopsis
        This function calculates the number of days until Christmas
       .Description
        This function calculates the number of days until Christmas
       .Example
        DaysTilChristmas
       .Notes
        Ed is really awesome
       .Link
        Http://blog.edgoad.com
     #>
        $Christmas=Get-Date("25 Dec " + (Get-Date).Year.ToString() + " 7:00 AM")
        $Today = (Get-Date)
        $TimeTilChristmas = $Christmas - $Today
        Write-Host $TimeTilChristmas.Days "Days 'til Christmas"
    }
  3. Once the function is created, we either type it or copy/paste it into a PowerShell console.

  4. Finally, we simply call the function by the name, Get-DaysTilChristmas.

How it works...

In the first step, we are attempting to find out how many days until Christmas using the basic PowerShell commands. We begin by using the Get-Date command to calculate the exact date of Christmas and put this into a variable named $Christmas. Actually, we are calculating the date and time until 7 a.m. Christmas morning—in this case, the time I plan to begin opening presents.

Next, we execute the Get-Date function without any parameters to return the current date and time into another variable named $Today. We create a third variable named $TimeTilChristmas, and subtract our two dates from each other. Finally, we write out the number of days remaining.

Note

Note: This assumes that the script is being executed before December 25th in the year. If this script is run after the 25th of December, a negative number of days will be returned.

The second step uses exactly the same commands as the first, except with the commands being included in a function. The Function command bundles the code into a reusable package named Get-DaysTilChristmas.

The function is input into PowerShell manually, via copy/paste or other methods. To use the function once it is created, just call it by its name.

At its simplest, a function is composed of the Function keyword, a function name, and commands encapsulated in curly braces.

Function FunctionName{
    # commands go here
}

The benefit of packaging the code as a function is that now it can be accessed by a name, without having to retype the original commands. Simply running Get-DaysTilChristmas again and again will continue to run the function and return the results.

There's more...

  • Function scope: Custom functions are traditionally limited to the currently active user session. If you create a function such as Get-DaysTilChristmas, and then open a new PowerShell window, the function will not be available in the new session, even though it is still available in the original session. Additionally, if you close your original session, the function will be removed from the memory and won't be available until it is re-entered.

  • Variable types: It may be interesting to note that the variables $Christmas and $Today are of different types than $TimeTilChristmas. The first two are date and time variables which refer to a specific point in history (year, month, day, hour, minute, second, millisecond, ticks). $TimeTilChristmas however is a time span; which refers to a length of time (day, hour, minute, second, millisecond, ticks), relative to a specific time. The type of a variable can be viewed by typing $<variableName>.GetType() as shown in the following screenshot:

  • Returning content: This function in its current form returns the number of days until Christmas, but that is all. Because the function uses date and time variables, it can easily include the number of hours, minutes, and seconds as well. See Get-Date | Get-Member for a list of properties that can be accessed.

  • Naming of functions and commands in PowerShell: Commands in PowerShell are traditionally named in a verb-noun pair, and for ease of use, a similar process should be used when naming custom functions. You can see in this example, we named the function Get-DaysTilChristmas, the verb Get, tells us that we are getting something. The noun DaysTilChristmas tells us what object we are working with. There are several common verbs such as Get, Connect, Find, and Save that should be used when possible. The noun in the verb-noun pair is often based on the object you are working with or the task you are doing. A full list of verbs for PowerShell can be found by executing Get-Verb.