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)

Script it (Advanced)


This recipe elaborates CMDLETs and the parameters that are introduced in Version 3 and can be useful to write efficient scripts with optimized efforts.

Getting ready

We have the default ISE module introduced in PowerShell Version 3.0.

How to do it...

  1. The following command statements create an ISE snippet that is reusable in any script. The Text parameter carries the actual string that is supplied as the snippet. We can also specify the Description, Title, and Author parameters if required.

    PS C:\ > $Script = @' 
    Hello Everyone
    Snippet is awesome 
    '@
    PS C:\ > New-IseSnippet -Description TestSnippet -Text $Script -Title TestSnippet –Author "Harshul"
    

    Note

    You should supply relevant information as text. I, for example, have used random words.

  2. The following command statement imports snippets from the shared path, \\Share\Snippets, recursively:

    PS C :\> Import-IseSnippet -Path \\Share\Snippets -Recurse
    

    Note

    The default execution policy setting on Windows Server 2012 R2 Preview is RemoteSigned. On Windows 8.1 Preview, there is no change in the default setting.

How it works...

The New-IseSnippet CMDLET creates a code snippet that can be re-used in the Windows PowerShell ISE environment. The snippet can be a frequently used command, a small portion of text that you can define as a string. This CMDLET indeed creates a PS1XML file that contains the snippet data. Snippet files will be created in the form of <SnippetTitle>.Snippets.ps1xml.

Note

Snippet only works in the Windows PowerShell ISE environment.

There's more…

The following are a few more CMDLETs that can be helpful for writing a script quickly.

Get-IseSnippet

The Get-IseSnippet CMDLET returns PS1XML file objects that contain snippets defined in the console. This parameter doesn't have any parameters except for common parameters; for example:

PS C:\> Get-IseSnippet
    Directory: C:\Users\Harshul\Documents\WindowsPowerShell\Snippets
Mode      LastWriteTime     Length Name
----        -------------   ------ ----
-a---       8/29/2013 6:34 PM 1071 TestSnippet.snippets.ps1xml

Import-IseSnippet

The Import-IseSnippet CMDLET imports snippets from the specified module of the directory path.

Note

Imported snippets will only be available within the current session; it won't be copied to your local snippet directory.

Show-Command

The Show-Command CMDLET is very useful to newbies who need some assistance to construct a command statement. Show-Command provides a graphical input window where you can put all your input in Graphical User Interface, and PowerShell will construct a command statement for you based on your inputs. There are options to Run or Copy your code into the script from the graphical window itself. Try to execute the following command:

PS C :\> Show-Command Invoke-Command

If you use the Copy button to copy the code to the clipboard, it appears as follows:

PS C :\> Invoke-Command -ScriptBlock {Get-EventLog -LogName System} -AsJob -Authentication Default -ComputerName PSTest

Unblock-File

By default, if we download any script from the Internet, it is treated as an unreliable file, and we can't run it with the RemoteSigned execution policy. The Unblock-File CMDLET validates the script downloaded from the Internet and lets us open and execute the script under the RemoteSigned execution policy.

The following command statement retrieves the list of scripts available in C:\PSScripts, and it unblocks all the files:

PS C :\> Get-ChildItem -Path C:\PSScripts | Unblock-File

Tip

$MyInvocation is an automatic variable that stores information about the current execution. In PowerShell Version 3.0, it has the PSSCriptRoot and PSCommandPath properties that refer to the $PSScriptRoot and $PSCommandPath automatic variables' values respectively.

Restart-Computer

In PowerShell v3.0, the Restart-Computer CMDLET maintains a persistent connection throughout the execution, which serves the reboot problem in between the execution.

Refer to the following code:

PS C :\> Restart-Computer -ComputerName PSTest –Credential PSDomain\PSAdmin -WSManAuthentication Basic -Protocol WSMan 

The preceding command statement restarts the PSTest computer using the WSMan protocol with the PSDomain\PSAdmin privilege.

The following command statement restarts PSTest and waits for 500 seconds for the WinRM service to be up on the PSTest computer. It also uses the Delay parameter to specify the duration between queries to identify the status of the PSTest computer, whether it is restarted or not.

PS C :\> Restart-Computer -ComputerName PSTest -Wait -For WinRM -Timeout 500 -Delay 3

A number of parameters have been newly introduced with the Restart-Computer CMDLET. The following is the list of parameters:

  • -Delay <Int16>: This parameter only works with the Wait and For parameters. It defines the duration to wait for the service to be started (specified with the For parameter). The default value for this parameter is 5 (seconds).

  • -For <WaitForServiceTypes>: This parameter specifies the service type to wait for after the computer is restarted. The accepted values are as follows:

    • Default: This waits until PowerShell restarts

    • PowerShell: This continues to work with the remote session

    • WMI: This queries the WMI class Win32_ComputerSystem for the computer

    • WinRM: This can create a remote PowerShell session

  • -Timeout <Int32>: This parameter provides the time-out duration after which it returns to the command prompt even though the computer is not restarted. The default value is -1; this states that the time-out duration is infinitely long.

  • -Wait [<SwitchParameter>]: This parameter is used when we need to restart in the middle of a script or a workflow execution. Using this parameter, a script or a workflow will resume execution after the computer is restarted.

  • -DcomAuthentication <AuthenticationLevel>: This parameter explicitly provides the authentication level to restart the computer using WMI. The accepted values for this parameter are as follows:

    • Call: This is for the Call-level COM authentication

    • Connect: This is for the Connect-level COM authentication

    • Default: This is for Windows authentication

    • None: This signifies that there is no COM authentication

    • Packet: This is for the Packet-level COM authentication

    • PacketIntegrity: This is for the Packet-Integrity-level COM authentication

    • PacketPrivacy: This is for the Packet-Privacy-level COM authentication

    • Unchanged: The authentication level is the same as the previous command

  • -Protocol <String>: This parameter provides a protocol for restarting computers. The parameter-accepted values are WSMan and DCOM. By default, it uses the DCOM protocol to restart the computer.

  • -WsmanAuthentication <String>: This parameter provides an authentication mechanism to verify the supplied credentials using the WSMan protocol. The accepted values are Basic, CredSSP, Default, Digest, Kerberos, and Negotiate. The default value for this parameter is Default.