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...
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 theDescription
,Title
, andAuthor
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.
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 theWait
andFor
parameters. It defines the duration to wait for the service to be started (specified with theFor
parameter). The default value for this parameter is5
(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 restartsPowerShell
: This continues to work with the remote sessionWMI
: This queries the WMI classWin32_ComputerSystem
for the computerWinRM
: 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 authenticationConnect
: This is for the Connect-level COM authenticationDefault
: This is for Windows authenticationNone
: This signifies that there is no COM authenticationPacket
: This is for the Packet-level COM authenticationPacketIntegrity
: This is for the Packet-Integrity-level COM authenticationPacketPrivacy
: This is for the Packet-Privacy-level COM authenticationUnchanged
: 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 areBasic
,CredSSP
,Default
,Digest
,Kerberos
, andNegotiate
. The default value for this parameter isDefault
.