Home Cloud & Networking Windows Server 2012 Automation with PowerShell Cookbook

Windows Server 2012 Automation with PowerShell Cookbook

By EDRICK GOAD
books-svg-icon Book
eBook $36.99 $24.99
Print $60.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $36.99 $24.99
Print $60.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Understanding PowerShell Scripting
About 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.
Publication date:
March 2013
Publisher
Packt
Pages
372
ISBN
9781849689465

 

Chapter 1. Understanding PowerShell Scripting

In this chapter we will cover the following recipes:

  • Managing security on PowerShell scripts

  • Creating and using functions

  • Creating and using modules

  • Creating and using PowerShell profiles

  • Passing variables to functions

  • Validating parameters in functions

  • Piping data to functions

  • Recording sessions with transcripts

  • Signing PowerShell scripts

  • Sending e-mail

  • Sorting and filtering

  • Using formatting to export numbers

  • Using formatting to export data views

  • Using jobs

  • Dealing with errors in PowerShell

  • Tuning PowerShell scripts for performance

  • Creating and using Cmdlets

 

Introduction


This chapter covers the basics related to scripting with PowerShell. PowerShell was released in 2006 and is installed by default starting with Windows 7 and Server 2008R2. PowerShell is also available as a download for Windows XP, Windows Vista, and Server 2003. One of the main differences between PowerShell and VBScript/JScript, the other primary scripting languages for Windows, is that PowerShell provides an interactive runtime. This runtime allows a user to execute commands in real time, and then save these commands as scripts, functions, or modules to be used later.

Since its introduction, support for PowerShell has increased dramatically. In addition to managing Windows environments, Microsoft quickly created snap-ins for additional applications such as Exchange Server, the System Center suite, and clustering. Additional vendors have also created snap-ins for PowerShell, with some of the most popular being VMware and NetApp.

Many of the recipes presented here are the building blocks commonly used in PowerShell such as signing scripts, using parameters, and sorting/filtering data.

 

Managing security on PowerShell scripts


Due to the powerful capabilities of PowerShell, maintaining a secure environment is important. Executing scripts from untrustworthy sources could damage data on your system and possibly spread viruses or other malicious code. To deal with this threat, Microsoft has implemented Execution Policies to limit what scripts can do.

Note

The execution policies only limit what can be performed by scripts, modules, and profiles, these policies do not limit what commands are executed in the interactive runtime.

How to do it...

In this recipe, we will view the system's current execution policy and change it to suit various needs. To do this, carry out the following steps:

  1. To find the system's current execution policy, open PowerShell and execute Get-ExecutionPolicy.

  2. To change the system's execution policy, run Set-ExecutionPolicy <policy name> command.

  3. To reset the execution policy to the system default, set the policy to Undefined.

  4. To change the execution policy for a specific session, go to Start | Run and enter PowerShell.exe –ExecutionPolicy <policy name>.

How it works...

When a script is executed, the first thing PowerShell does is, determine the system's execution policy. By default, this is set to Restricted, which blocks all the PowerShell scripts from running. If the policy allows signed scripts, it analyzes the script to confirm it is signed and that the signature is from a trusted publisher. If the policy is set to unrestricted, then all the scripts run without performing checking.

Setting the execution policy is simply done via the command. Here we see several examples of viewing and setting the execution policy to various settings. There are six execution policies as follows:

  • Restricted: No scripts are executed. This is the default setting.

  • AllSigned: This policy allows scripts signed by a trusted publisher to run.

  • RemoteSigned: This policy requires remote scripts to be signed by a trusted publisher.

  • Unrestricted: This policy allows all scripts to run. It will still prompt for confirmation for files downloaded from the internet.

  • Bypass: This policy allows all scripts to run and will not prompt.

  • Undefined: This policy resets the policy to the default.

When changing the execution policy, you will be prompted via a command line or pop-up window to confirm the change. This is another level of security, but can be disabled by using the –Force switch.

There's more...

  • Approving publishers: When running scripts from new publishers, there are two primary methods for approving them. The first method is to open the certificates MMC on the local computer and import the signer's CA into the Trusted Publishers store. This can be done manually or via a group policy. The second method is to execute the script, and when prompted, approve the publisher.

  • Defining execution policy via GPO: The execution policy for individual computers, groups, or enterprise can be controlled centrally using group policies. The policy is stored under Computer Configuration | Policies | Administrative Templates | Windows Components | Windows PowerShell. Note however that this policy only applies to Windows 7/2008 or newer operating systems.

  • Permissions to change the execution policy: Changing the execution policy is a system-wide change, and as such requires administrator level permissions. With Windows default access controls in place, this also requires you to start PowerShell as an administrator.

    Changing the execution policy requires elevated permissions to run, so you may need to open PowerShell with Run as administrator to set the policy. If you are attempting to change the policy without sufficient permission, an error will be returned.

Tip

Best practice is to enforce some level of signature checking in most environments. In Dev/Test environments, it may be common to set the policy to Unrestricted to expedite testing, but it is always suggested to require fully signed scripts in production environments.

 

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.

 

Creating and using modules


Modules are a way of grouping functions for similar types of tasks or components into a common module. These modules can then be loaded, used, and unloaded together as needed. Modules are similar in concept to libraries in the Windows world—they are used to contain and organize tasks, while allowing them to be added and removed dynamically.

An example of a module is working with the DNS client. When working with the DNS client, you will have various tasks to perform: get configuration, set configuration, resolve hostname, register client, and so on. Because all of these tasks have to do with a common component, the DNS client, they can be logically grouped together into the DNSClient module. We can then view the commands included in the module using Get-Command –Module DnsClient as shown in the following screenshot:

Here we will show how to create a module for containing common functions that can be loaded as a unit. Because modules typically group several functions together, we will start off by creating multiple functions.

For our recipe, we will be creating a module named Hello. In this example, we have created two simple "Hello World" type functions. The first simply replies "Hello World!", while the second takes a name as a variable and replies "Hello <name>".

How to do it...

Carry out the following steps:

  1. Create several functions that can be logically grouped together.

    Function Get-Hello
    {
        Write-Host "Hello World!"
    }
    Function Get-Hello2
    {
        Param($name)
        Write-Host "Hello $name"
    } 
  2. Using the PowerShell ISE or a text editor, save the functions into a single file name Hello.PSM1.

  3. If the folder for the module doesn't exist yet, create the folder.

    $modulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\Hello"
    if(!(Test-Path $modulePath))
    {
        New-Item -Path $modulePath -ItemType Directory
    }
  4. Copy Hello.PSM1 to the new module folder.

    $modulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\Hello"
    Copy-Item -Path Hello.PSM1 -Destination $modulePath
  5. In a PowerShell console, execute Get-Module –ListAvailable to list all the available modules:

    Note

    A large list of modules will likely be returned. The modules in the current user's profile will be listed first, and you may need to scroll up the PowerShell window to see them listed.

  6. Run Import-Module Hello to import our new module.

    Note

    See the recipes Managing Security on PowerShell Scripts and Signing PowerShell Scripts for information about the security requirements for using modules.

  7. Run Get-Command –Module Hello to list the functions included in the module:

  8. Execute the functions in the module as normal:

How it works...

We start off by identifying several functions or commands to group together as a module. These commands do not necessarily have to relate to each other, but it is often best to organize them as well as possible. The commands are then saved into a single file with a .PSM1 file extension. This file extension indicates to PowerShell that the file is a PowerShell module.

The module is then stored in the user's profile directory. If the folder doesn't already exist, we create a new folder named the same as the module. Once the folder exists, we copy the .PSM1 file into the folder. PowerShell automatically searches this location for new modules to load.

Note

There are two locations PowerShell looks for installed modules: C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ and %userprofile%\Documents\WindowsPowerShell\Modules. The first location is used by the entire system and requires administrative permission to access; most third party modules are installed here. The second location is user specific and does not require elevated rights to install scripts.

Once saved, we can load the module to the memory. The command Import-Module loads the contents of the module and makes the commands available for use. We can then view the contents of the module using Get-Command –Module Hello. This returns all publicly available functions in the module.

Note

Modules are viewed by PowerShell similar to scripts and they rely on the same security requirements as other scripts. Because of these restrictions, it is best practice to sign your modules once they have been created.

Finally, once the module is loaded, we can execute the included commands.

There's more...

  • Auto-loading of modules: PowerShell 3.0 automatically imports modules as they are needed. While it is best practice to load and unload modules, you do not necessarily have to use Import-Module prior to accessing the functions contained within. As you can see in the following screenshot, I listed the currently loaded modules using Get-Module. Once I confirmed my new Hello module was not loaded, I then execute the Get-Hello2 function in the module which completed successfully. Executing Get-Module again shows the module has been automatically loaded.

  • Module manifest: In addition to the modules themselves, you can also create a module manifest. A module manifest is a file with a .PSD1 extension that describes the contents of the module. Manifests can be useful because they allow for defining the environment in which a module can be used, its dependencies, additional help information, and even which set of commands to make available. The following code is a basic example of creating a manifest for our Hello World module:

    New-ModuleManifest -Path "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\Hello\Hello.PSD1" -Author "Ed Goad" -Description "Hello World examples" -HelpInfoUri "http://blog.edgoad.com" -NestedModules 'Hello.PSM1'  

    Once the manifest is created, we can view the manifest properties using the following code:

    Get-Module Hello -ListAvailable | Format-List -Property * 
 

Creating and using PowerShell profiles


User profiles are used to set up user customized PowerShell sessions. These profiles can be blank, contain aliases, custom functions, load modules, or any other PowerShell tasks. When you open a PowerShell session, the contents of the profile are executed the same as executing any other PowerShell script.

How to do it...

In this recipe, we will modify the PowerShell console profile for the current user on the current host. By default the profile file does not exist, so we will create the file, and then configure it to create a transcript of our actions. To do this, carry out the following steps:

  1. Open the PowerShell console (not the ISE) and list your current profile locations by executing $PROFILE or $PROFILE | Format-List * -Force|:

  2. If the CurrentUserCurrentHost profile file doesn't already exist, create the folder and file structure:

    $filePath = $PROFILE.CurrentUserCurrentHost
    if(!(Test-Path $filePath))
    {
        New-Item -Path $filePath -ItemType File
    }
  3. Edit the CurrentUserCurrentHost profile by opening it in a text editor. Make the necessary changes and save the file.

Tip

NOTE: It is best practice to sign your profiles after making changes. This ensures that the profile is secure and hasn't been unintentionally changed.

More information about code signing in PowerShell can be found in the recipe Signing PowerShell scripts

How it works...

When a PowerShell session is started, the profile files are executed before the session is handed over to the user. At that time, any aliases or modules that were loaded will be in effect. Additionally, any background commands, such as Start-Transcript, will continue to operate in the background.

We start by opening PowerShell and listing our profile files. By default, $PROFILE command only returns the CurrentUserCurrentHost profile. By piping the output through Format-List with the –Force switch, we can see all applicable profile files.

Note

In this example we are specifically using the PowerShell console, instead of the PowerShell ISE, because the Start-Transcript command is only supported in the console.

There's more…

There are six user profile files in total, and they are applied to PowerShell sessions one at a time. First the more general profiles, such as AllUsersAllHosts are applied, ending with more specific profiles such as CurrentUserCurrentHost. As the individual profiles are applied, any conflicts that arise are simply overwritten by the more specific profile.

Not all six profiles are used at a time, and by default, these profiles are empty. Two of the profiles are specific to the PowerShell console, and two of them are specific to the PowerShell ISE. At the most, you can have four active profiles on a given session.

See also

Latest Reviews (3 reviews total)
I honestly haven't started reading it yet....I'm in the middle of studying for my MCSA, but I wouldn't have bought it if it wasn't a good book.
Windows Server 2012 Automation with PowerShell Cookbook
Unlock this book and the full library FREE for 7 days
Start now