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)

Setting default parameter values (Intermediate)


We will learn to set the default parameter values.

Getting ready

$PSDefaultParameterValues is a default preference variable introduced in PowerShell v3.0. This variable sets the custom parameter values to specified CMDLETs and functions. It maintains a hash table to store all of the defined values.

How to do it...

Try the following test code to set the default parameter values:

  1. The following command statement sets the localhost value to the parameter name ComputerName for all CMDLETs that have Invoke as a verb:

    PS C :\> $PSDefaultParameterValues=@{"Invoke-*:ComputerName"="localhost"} 
    

    Tip

    $PSDefaultParameterValues accepts wildcard characters. Also, we can use the ; (semicolon) character to assign multiple parameter values to the $PSDefaultParameterValues variable.

  2. The following command provides the computer name, specified as C:\Servers.txt, to the ComputerName parameter for all CMDLETs that have Invoke as a verb:

    $PSDefaultParameterValues=@{"Invoke-*:ComputerName"={Get-Content C:\Servers.txt} }
    

How it works...

The following are the syntaxes to define the $PSDefaultParameterValues preference variable:

  • $PSDefaultParameterValues=@{"<CmdletName>:<ParameterName>"="<DefaultValue>"}: This syntax maps default values to the combination of the specified CMDLET and ParameterName.

  • $PSDefaultParameterValues=@{"<CmdletName>:<ParameterName>"={<ScriptBlock>}}: This syntax provides the facility to pass ScriptBlock as the default value to the combination of the specified CMDLET and ParameterName.

  • $PSDefaultParameterValues["Disabled"]=$true | $false: This syntax enables/disables the behavior of the $PSDefaultParameterValues variable.

  • $PSDefaultParameterValues[Disabled]=$true: This command statement maintains the list of values in $PSDefaultParameterValues, but it disables its behavior in the current session. You can reset its behavior by using the following syntax: $PSDefaultParameterValues[Disabled]=$false. There is also an alternative to control the behavior of $PSDefaultParameterValues.

    • To disable the behavior, use $PSDefaultParameterValues.Add("Disabled", $true).

    • To enable the behavior use $PSDefaultParameterValues.Remove("Disabled").

      The previous value of this variable will again be in effect in the current PowerShell console.

There's more…

The following are a couple of functionality changes with respect to Windows PowerShell v4.0.

PipelineVariable – a new common parameter

This common parameter allows us to store the current pipeline object in the specified variable. This technique is very useful when dealing with multiple commands in a pipeline with transformative information. In such cases, we will sometimes lose context and be unable to retrieve the data as and when required. We can use the pipeline variable to save the result and that can be passed through the remainder of the pipeline.

For example, in the case of System Center Orchestrator, this parameter helps to extend the context of iterative pipelines.

Collection filtering using method syntax

With the beginning of Windows PowerShell v4.0, we can now filter a collection of objects using a simplified where syntax when a method calls.

PS C :\> (Get-Command).where("Name -like *log")

The preceding command statement retrieves all the CMDLETs ending with the log keyword.

Prior to using this, we need to import the PSDesiredStateConfiguration module as collection filtering is a part of it.

PS C :\> Import-Module PSDesiredStateConfiguration
PS C :\> (Get-Command).where
Script              : $prop, $psop, $val = [string] $args[0] -split
                      '(-eq|-ne|-gt|-ge|-lt|-le|-like|-notlike|-match|-notmatch)'
                      $operation = @{ Prop = $prop.Trim(); Value = $val.Trim(); $psop = $true }
                      $this | where @operation
OverloadDefinitions : {System.Object where();}
MemberType          : ScriptMethod
TypeNameOfValue     : System.Object
Value               : System.Object where();
Name                : where
IsInstance          : False

The where() method is not limited to PowerShell 4.0 only. The following syntax can be used to enable this on systems with PowerShell v3.0 as well:

PS C :\> Update-TypeData -Force -MemberType ScriptMethod -MemberName where -TypeName System.Array -Value { $prop, $psop, $val = [string] $args[0] -split '(-eq|-ne|-gt|-ge|-lt|-le|-like|-notlike|-match|-notmatch)' $operation = @{ Prop = $prop.Trim(); Value = $val.Trim(); $psop = $true } $this | where @operation}

Run the preceding command statement, which enables the where method signature into your PowerShell 3.0 console, and execute commands as follows:

PS C :\> (Get-Command).where("Name -like *log")

This solution can be leveraged if you don't want to import the PSDesireStateConfiguration module explicitly.