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)

How to import modules to the console (Simple)


In this recipe, we will learn how to import modules to the console.

Getting ready

In previous versions, we used to run the Import-Module CMDLET to load specific modules onto a console, but now, in Version 3, there is no need to explicitly import modules that are specified in $env:PSModulePath. There are a few more modules that come along with the Version 3 consoles.

How to do it...

Let's try to put it in an example:

  1. Have a look at the following command:

    PS C:\ > Get-Module
    

    Check the following list of loaded modules in the console at present:

    Module type

    Name

    Exported commands

    Manifest

    Microsoft.PowerShell.Management

    Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content, and so on

    The preceding command lists out all the modules loaded in the current session.

    By default, the Microsoft.PowerShell.Mangement module is preloaded onto the console, even if you are opening it for the first time.

  2. Now, try to use following code:

    PS C :\> Get-Job
    

    It retrieves the Windows PowerShell background jobs that are running in the current session.

  3. Now, execute Get-Module again, using the following code:

    PS C :\> Get-Module
    

    Check the following list of loaded modules in the console at present:

    Module type

    Name

    Exported commands

    Manifest

    Microsoft.PowerShell.Management

    Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content, and so on

    Manifest

    Microsoft.PowerShell.Utility

    Add-Member, Add-Type, Clear-Variable, Compare-Object, and so on

    If you are trying to execute CMDLETs apart from the loaded modules, the Version 3 console automatically loads modules from the PSModulePath location onto a current session. In the preceding example, the Microsoft.PowerShell.Utility module is loaded once we have executed the Get-Job CMDLET onto the console.

  4. Going further:

    PS C :\> Get-CimSession
    

    The preceding command retrieves the CIM session objects from the current session.

  5. Have a look at the following command:

    PS C :\> Get-Module
    

    Check the following list of loaded modules in the console at present:

    Module type

    Name

    Exported commands

    Binary

    CimCmdlets

    Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance, Get-CimSession, and so on

    Manifest

    Microsoft.PowerShell.Management

    Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content, and so on

    Manifest

    Microsoft.PowerShell.Utility

    Add-Member, Add-Type, Clear-Variable, Compare-Object, and so on

    Now, the CimCmdlets module is also loaded onto the console because you are trying to execute the CMDLETs of that module file.

How it works…

For better understanding, let's get the list of the newly introduced modules in version 3.0. Have a look at the following command:

PS C :\> Get-Module -ListAvailable | where PowerShellVersion -eq '3.0'
Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules

Check the following list of available modules with PowerShell v3.0:

Module type

Name

Exported commands

Manifest

CimCmdlets

Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance, Get-CimSession, and so on

Script

ISE

New-IseSnippet, Import-IseSnippet, and Get-IseSnippet

Manifest

Microsoft.PowerShell.Diagnostics

Get-WinEvent, Get-Counter, Import-Counter, Export-Counter, and so on

Manifest

Microsoft.PowerShell.Host

Start-Transcript and Stop-Transcript

Manifest

Microsoft.PowerShell.Management

Add-Content, Clear-Content, Clear-ItemProperty, and Join-Path

Manifest

Microsoft.PowerShell.Security

Get-Acl, Set-Acl, Get-PfxCertificate, and Get-Credential

Manifest

Microsoft.PowerShell.Utility

Format-List, Format-Custom, Format-Table, and Format-Wide

Manifest

Microsoft.WSMan.Management

Disable-WSManCredSSP, Enable-WSManCredSSP, Get-WSManCredSSP, and Set-WSManQuickConfi

Binary

PSScheduledJob

New-JobTrigger, Add-JobTrigger, Remove-JobTrigger, and Get-JobTrigger

Manifest

PSWorkflow

New-PSWorkflowExecutionOption, New-PSWorkflowSession, and nwsn

Manifest

PSWorkflowUtility

Invoke-AsWorkflow

Sometimes, you have many modules placed in your PSModulePath location and they will be loaded onto your current session eventually, one-by-one, based on your CMDLET interaction. It will overhead for the current session to load all available modules. There is a way to restrict such behavior. In Version 3, a new preference variable has been introduced, named $PSModuleAutoloadingPreference.

It enables or disables autoloading behavior in modules. The default value is All. So, by default, it loads all the modules onto the console from the PSModulePath location, when and where required. Irrespective of the value of $PSModuleAutoloadingPreference, you can leverage the Import-Module CMDLET to load the required modules at any time.

$PSModuleAutoloadingPreference has three values listed as follows:

  • All: The modules are autoloaded if you are using their CMDLETs for the first time.

  • Module Qualified: With this value, you need to explicitly provide the module name with the CMDLET like TestModule\TestCmdlet. For example, PSScheduledJob\New-JobTrigger.

  • None: It disables auto importing behavior in modules. You need to manually import the module using the Import-Module CMDLET. To restrict autoloading behavior in modules, run the following code:

    PS C :\> $global:PSModuleAutoloadingPreference="None"
    

There's more…

With Windows PowerShell v3.0, you can log execution events for Windows PowerShell modules.

LogPipelineExecutionDetails

In previous versions, this feature was supported by snap-ins alone. If the LogPipelineExecutionDetails property value is set to $True, it writes execution events from a current session into the Windows PowerShell log, which is in the event viewer. This setting is limited to the current session; if you re-open the session, you need to manually set the property value again.

Use the following code to enable logging and set the property value to $True for the PSScheduledJob module:

PS C :\> Import-Module -Name PSScheduledJob
PS C :\> $Temp = Get-Module -Name PSScheduledJob
PS C :\> $Temp.LogPipelineExecutionDetails = $True

To disable module logging, you can use the same code sequence using the property value $False.

You can explicitly perform this property value setting using the Group Policy setting. This setting will be applicable to all the sessions for a specified module. "Turn on Module Logging" is available at the following paths:

  • Computer Configuration\Administrative Templates\Windows Components\Windows PowerShell

  • User Configuration\Administrative Templates\Windows Components\Windows PowerShell

The policy defined for the user takes precedence over the computer policy and both the policies take precedence over the property value of the LogPipelineExecutionDetails parameter.

For example, you can find the event log entries for Windows PowerShell using the following code:

PS C:\> Get-EventLog -LogName "Windows PowerShell" | Format-Table -AutoSize –Wrap

Get-Module

There is one more parameter introduced with the Get-Module CMDLET with the release of Windows Powershell 4.0: -FullyQualifiedName <String[]>. It accepts parameter values as ModuleSpecification objects. The FullyQualifiedName parameter has a specified format as shown:

@{ModuleName = "modulename"; ModuleVersion = "version_number"}

We can use either Name or FullyQualifiedName with the Get-Module CMDLET. We cannot use both together as they are mutually exclusive.

Note

In PowerShell v4.0, Get-Module displays module versions in the output as Version column.