Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Instant Windows PowerShell Guide

You're reading from   Instant Windows PowerShell Guide Enhance your knowledge of Windows PowerShell and get to grips with its latest features

Arrow left icon
Product type Paperback
Published in Nov 2013
Publisher Packt
ISBN-13 9781849686785
Length 86 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Harshul Patel Harshul Patel
Author Profile Icon Harshul Patel
Harshul Patel
Arrow right icon
View More author details
Toc

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.

You have been reading a chapter from
Instant Windows PowerShell Guide
Published in: Nov 2013
Publisher: Packt
ISBN-13: 9781849686785
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image