Book Image

Instant Windows PowerShell Guide

By : Harshul Patel
Book Image

Instant Windows PowerShell Guide

By: Harshul Patel

Overview of this book

Windows PowerShell has become a booming scripting language over the last couple of years. It has extensive support with an ample number of vendor products, providing a standardized platform for automation and administration. It has massive support for all Microsoft products which creates a layer that can easily automate everything. In the latest version, the PowerShell team has introduced much more functionality with thousands of CMDLETs, part of various modules.This book is a quick reference guide to enable you to get the most out of the latest Windows PowerShell techniques. In this book, you will find new enhancements in the latest version of PowerShell with some helpful examples. This book enables you to quickly move from older versions of PowerShell to Version 3.0 and Version 4.0.This practical, example-oriented book helps you to overcome the difficulty of using and discovering CMDLETs by providing precise information about everything that has been newly introduced in the latest version of Windows PowerShell. It also focuses on the new configuration management system with the help of DSC as a new feature of Windows PowerShell v4.0.You will learn how to use the newly introduced CMDLETs and parameters to perform daily routine tasks. You will also learn how to administer the servers remotely and maintain persistent sessions to provide continuity. You will gain an insight into writing efficient scripts by using various parameters, snippets, and workflows to gain more productivity. You will also be introduced to various modules like CimCmdlets, PSScheduledJob, PSDesiredStateConfiguration, and so on in order to enhance your scripts with the latest instrumentation. Finally this book will make you aware of the capabilities of PowerShell v4.0 and how to fully leverage the functionality introduced in the new version.
Table of Contents (7 chapters)

Dealing with PSDrive (Simple)

A few changes have been introduced with respect to files and drives in Windows PowerShell Version 3.0. Windows PowerShell has a built-in drive mechanism for things such as registry, certificate, alias, function, variable, and so on. You can treat these drives as filesystems.

Getting ready

There are some functionality changes when we create a new custom PSDrive using PowerShell Version 3.0. Let's walk through them.


This CMDLET creates a new temporary or persistent drive with various Windows PowerShell provider types.

How to do it...

  1. You can get the list of default Windows PowerShell providers by executing the following CMDLET:

    PS C :\> Get-PSProvider
    Name         Capabilities                         Drives
    ----         ------------                         ------
    Alias        ShouldProcess                        {Alias}
    Environment  ShouldProcess                        {Env}
    FileSystem   Filter, ShouldProcess, Credentials   {C, D, E, F}
    Function     ShouldProcess                        {Function}
    Registry     ShouldProcess, Transactions          {HKLM, HKCU}
    Variable     ShouldProcess                        {Variable}
    Certificate  ShouldProcess                        {Cert}
    WSMan        Credentials                          {WSMan}
  2. The following command statement creates a new persistent PSDrive named T from the location \\FileSrv\Temp; it uses the credential PSDomain\PSAdmin and it prompts for a password:

    PS C :\> New-PSDrive -Name T -PSProvider FileSystem -Root \\FileSrv\Temp -Credential PSDomain\PSAdmin -Persist

    The Credential parameter is generally used to provide explicit user credentials that have the privilege to create new PSDrives. By default, it takes the current user session credential.

    Using the Persist parameter name, we ensure that the new PSDrive acts as a normal filesystem drive with a new drive letter, for example, T. You can further use the T drive using file explorer or the net use utility.

How it works…

Let's get the full information of the PowerShell drive named T earlier:

PS C :\> Get-PSDrive -Name T
Name         Provider        Root
----         --------        ----
T            FileSystem      T:\

In Version 3.0, the following are a few functionality changes with respect to the New-PSDrive CMDLET.

  • -Persist: Using the –Persist parameter name with the New-PSDrive CMDLET, you can create mapped network drives that are not limited to the current Windows PowerShell sessions. They are stored in the Windows configuration and, moreover, you can open them using file explorer or the net use utility.

  • -Credential: If you are using the UNC path to create New-PSDrive, you can leverage the Credential parameter name that is introduced in Windows PowerShell v3.0 along with the New-PSDrive CMDLET. Apart from the UNC path, the Credential parameter name is not mandatory with all the other possible scenarios.

  • External drives: If you attach any external drive to your local computer, it automatically creates a new PSDrive that represents your external drive. We need not restart our machine to see these changes in effect. Likewise, if you remove the drive, Windows PowerShell automatically deletes the PSDrive that was mapped with your external drive earlier.


Issues with mounting and unmounting VHDs using the FileSystem provider in Windows PowerShell 4.0 have been fixed. Windows PowerShell is now able to detect new drives when they are mounted in the same session.

There's more…

There are couple of more parameters that are introduced with various CMDLETs in Version 3. The information is as described in this section.


In Version 3.0, the Get-Credential CMDLET has one additional parameter name called the Message parameter. Using the Message parameter, you can specify customized messages to the users on prompted credential windows.

For example:

PS C :\> Get-Credential -Message "Enter your valid Username and Password" -UserName PSDomain\PSAdmin


The Select-Object CMDLET is generally used to select objects or object properties. In Version 3.0, it is known by a new parameter name called Wait, which is used to turn off the object optimization.

Usually, Windows PowerShell has the behavior to generate all objects and throw them to the pipeline flawlessly. If you use Select-Object with either the First or Index parameter and proceed with the Wait parameter, the console will stop creating further objects after the specified value.

PS C :\> Get-Process | Select-Object Name -First 5 –Wait

The previous command statement retrieves the first five process objects instead of generating all the process objects for running processes.


With PowerShell v4.0, Select-Object –Expand no longer fails or generates an exception if the value of the property is null or empty.


In the previous versions of Windows PowerShell, if you have the header row value as a null value, the Import-Csv CMDLET fails. But, in Version 3.0, the Import-Csv CMDLET has the Header parameter name, which helps to overcome this error.

The Header parameter name manually adds the header row to the CSV file before importing it to the console. It gives a warning message with the output displayed.

For example, assume there is a CSV file named Services.csv placed in a present directory with all the information about the running services stored in it with a null header row value:

PS C :\> $header = "Current State", "Service Name", "Description"

The $header variable contains manually defined header row values.

PS C :\> Import-Csv –Path .\Services.csv -Header $header 

The preceding command statement manually attaches header row values and imports the specified CSV file to the console.

In PowerShell v3.0, the Import-Csv CMDLETs don't work well if your CSV file has any blank lines; the output spits empty objects. But, in PowerShell v4.0, blank lines are ignored and the Import-Csv CMDLET works as expected.

Dealing with JSON-formatted objects

In Version 3.0, the team has extended covert CMDLET's chains to ConvertTo-Json and ConvertFrom-Json. In previous versions, we had similar CMDLETs, for example, ConvertTo-Csv, ConvertFrom-Csv, ConvertTo-Html, ConvertFrom-Html, and so on.

The ConvertTo-Json CMDLET converts Windows PowerShell objects to JSON-formatted string objects.

PS C :\> Get-Process | ConvertTo-Json

The preceding command statement returns JSON-formatted process string objects. The ConvertTo-Json CMDLET converts all process objects into JSON-formatted string objects.

The ConvertFrom-Json CMDLET behaves exactly opposite to the ConvertTo-Json CMDLET. It converts JSON-formatted string objects to custom Windows PowerShell objects.

PS C :\> Get-Process | ConvertTo-Json | ConvertFrom-Json

The preceding command statement returns custom process objects. The ConvertTo-Json CMDLET converts all process objects into JSON-formatted string objects. Again, the ConvertFrom-Json CMDLET converts all JSON-formatted string objects into custom Windows PowerShell objects.


ConvertTo-Json and ConvertFrom-Json can now accept terms within double quotes and its error messages are now localizable.

Windows PowerShell custom object enhancements

In Version 2.0, we have the New-Object CMDLET to create Windows PowerShell objects as syntaxes:

PS C :\> $Objv2 = New-Object –TypeName PSObject -Property @{x=1; y=2; z=3}

This creates a new Windows PowerShell object with three mapped property values.

PS C :\> $Objv2 | Format-List
y: 2
z: 3
x: 1

In Version 3.0, we have the PSCustomObject type to create Windows PowerShell custom object as syntaxes:

PS C :\> $Objv3 = [PSCustomObject]@{x=1; y=2; z=3}

This also creates a custom Windows PowerShell object with three mapped values.

PS C :\> $Objv3 | Format-List
x: 1
y: 2
z: 3

In both the cases, it creates PSCustomObject using NoteProperties.

PS C :\> $Objv3 | Get-Member

It lists out all the methods and node properties with respect to PSCustomObject.

TypeName: System.Management.Automation.PSCustomObject
Name            MemberType     Definition
----            ----------     ----------
Equals          Method         bool Equals(System.Object obj)
GetHashCode     Method         int GetHashCode()
GetType         Method         type GetType()
ToString        Method         string ToString()
x               NoteProperty   System.Int32 x=1
y               NoteProperty   System.Int32 y=2
z               NoteProperty   System.Int32 z=3

The only benefit we get out of this is that it maintains the property order, rendering it to be utilized reliably.