Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Windows Server 2012 Automation with PowerShell Cookbook

You're reading from   Windows Server 2012 Automation with PowerShell Cookbook If you work on a daily basis with Windows Server 2012, this book will make life easier by teaching you the skills to automate server tasks with PowerShell scripts, all delivered in recipe form for rapid implementation.

Arrow left icon
Product type Paperback
Published in Mar 2013
Publisher Packt
ISBN-13 9781849689465
Length 372 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
EDRICK GOAD EDRICK GOAD
Author Profile Icon EDRICK GOAD
EDRICK GOAD
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

Windows Server 2012 Automation with PowerShell Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Understanding PowerShell Scripting 2. Managing Windows Network Services with PowerShell FREE CHAPTER 3. Managing IIS with PowerShell 4. Managing Hyper-V with PowerShell 5. Managing Storage with PowerShell 6. Managing Network Shares with PowerShell 7. Managing Windows Updates with PowerShell 8. Managing Printers with PowerShell 9. Troubleshooting Servers with PowerShell 10. Managing Performance with PowerShell 11. Inventorying Servers with PowerShell 12. Server Backup 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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image