Powershell Design
Design
Windows PowerShell can execute four kinds of named commands:[1]
- cmdlets, which are .NET programs designed to interact with PowerShell
- PowerShell scripts (files suffixed by .ps1)
- PowerShell functions
- standalone executable programs
If a command is a standalone executable program, PowerShell.exe
launches it in a separate process; if it is a cmdlet, it is executed in the PowerShell process. PowerShell provides an interactive command line interface, wherein the commands can be entered and their output displayed. The user interface, based on the Win32 console, offers customizable tab completion but lacks syntax highlighting. PowerShell enables the creation of aliases for cmdlets, which are textually translated by PowerShell into invocations of the original commands. PowerShell supports both named and positional parameters for commands. In executing a cmdlet, the job of binding the argument value to the parameter is done by PowerShell itself, but for external executables, arguments are parsed by the external executable independently of PowerShell interpretation.[citation needed]
The PowerShell Extended Type System (ETS) is based on the .NET type system, but with extended semantics (for example, propertySets and third-party extensibility). For example, it enables the creation of different views of objects by exposing only a subset of the data fields, properties, and methods, as well as specifying custom formatting and sorting behavior. These views are mapped to the original object using XML-based configuration files.[2]
Cmdlets
Cmdlets are specialized commands in the PowerShell environment that implement specific functions. These are the native commands in the PowerShell stack. Cmdlets follow a Verb-Noun naming pattern, such as Get-ChildItem, helping to make them self-descriptive.[3] Cmdlets output their results as objects, or collections thereof (including arrays), and can optionally receive input in that form, making them suitable for use as recipients in a pipeline. But whereas PowerShell allows arrays and other collections of objects to be written to the pipeline, cmdlets always process objects individually. For collections of objects, PowerShell invokes the cmdlet on each object in the collection, in sequence.[3]
Cmdlets are specialized .NET classes, which the PowerShell runtime instantiates and invokes when they are run. Cmdlets derive either from Cmdlet
or from PSCmdlet
, the latter being used when the cmdlet needs to interact with the PowerShell runtime.[3] These base classes specify certain methods - BeginProcessing()
, ProcessRecord()
and EndProcessing()
- which the cmdlet's implementation overrides to provide the functionality. Whenever a cmdlet is run, these methods are invoked by PowerShell in sequence, with ProcessRecord()
being called if it receives pipeline input.[4] If a collection of objects is piped, the method is invoked for each object in the collection. The class implementing the Cmdlet must have one .NET attribute - CmdletAttribute
- which specifies the verb and the noun that make up the name of the cmdlet. Common verbs are provided as an enum.[5][6]
If a cmdlet receives either pipeline input or command-line parameter input, there must be a corresponding property in the class, with a mutator implementation. PowerShell invokes the mutator with the parameter value or pipeline input, which is saved by the mutator implementation in class variables. These values are then referred to by the methods which implement the functionality. Properties that map to command-line parameters are marked by ParameterAttribute
[7] and are set before the call to BeginProcessing()
. Those which map to pipeline input are also flanked by ParameterAttribute
, but with the ValueFromPipeline
attribute parameter set.[8]
The implementation of these cmdlet classes can refer to any .NET API and may be in any .NET language. In addition, PowerShell makes certain APIs available, such as WriteObject()
, which is used to access PowerShell-specific functionality, such as writing resultant objects to the pipeline. Cmdlets can use .NET data access APIs directly or use the PowerShell infrastructure of PowerShell Providers, which make data stores addressable using unique paths. Data stores are exposed using drive letters, and hierarchies within them, addressed as directories. Windows PowerShell ships with providers for the file system, registry, the certificate store, as well as the namespaces for command aliases, variables, and functions.[9] Windows PowerShell also includes various cmdlets for managing various Windows systems, including the file system, or using Windows Management Instrumentation to control Windows components. Other applications can register cmdlets with PowerShell, thus allowing it to manage them, and, if they enclose any datastore (such as databases), they can add specific providers, as well.[citation needed]
In PowerShell V2, a more portable version of Cmdlets called Modules have been added. The PowerShell V2 release notes state:
"Modules allow script developers and administrators to partition and organize their Windows PowerShell code in self-contained, reusable units. Code from a module executes in its own self-contained context and does not affect the state outside of the module. Modules also enable you to define a restricted runspace environment by using a script."[citation needed]
Pipeline
PowerShell implements the concept of a pipeline, which enables the output of one cmdlet to be piped as input to another cmdlet.
As with Unix pipelines, PowerShell pipelines are used to compose complex commands, using the |
operator to connect stages. However, the PowerShell pipeline differs from Unix pipelines in that stages execute within the PowerShell runtime rather than as a set of processes coordinated by the operating system, and structured .NET objects, rather than byte streams, are passed from one stage to the next. Using objects and executing stages within the PowerShell runtime eliminates the need to serialize data structures, or to extract them by explicitly parsing text output.
An object can also encapsulate certain functions that work on the contained data, which become available to the recipient command for use.
Because all PowerShell objects are .NET objects, they share a .ToString()
method, which retrieves the text representation of the data in an object.
Scripting
Windows PowerShell includes a dynamically typed scripting language which can implement complex operations using cmdlets imperatively. The scripting language supports variables, functions, branching (if-then-else
), loops (while
, do
, for
, and foreach
), structured error/exception handling and closures/lambda expressions,[10] as well as integration with .NET. Variables in PowerShell scripts have names that start with $
; they can be assigned any value, including the output of cmdlets. Strings can be enclosed either in single quotes or in double quotes: when using double quotes, variables will be expanded even if they are inside the quotation marks. Enclosing the path to a file in braces preceded by a dollar sign (as in ${C:\foo.txt}
) creates a reference to the contents of the file. If it is used as an L-value, anything assigned to it will be written to the file. When used as an R-value, the contents of the file will be read. If an object is assigned, it is serialized before being stored.[citation needed]
Object members can be accessed using .
notation, as in C# syntax. PowerShell provides special variables, such as $args
, which is an array of all the command line arguments passed to a function from the command line, and $_
, which refers to the current object in the pipeline.[11] PowerShell also provides arrays and associative arrays. The PowerShell scripting language also evaluates arithmetic expressions entered on the command line immediately, and it parses common abbreviations, such as GB, MB, and KB.[12][13]
Using the function
keyword, PowerShell provides for the creation of functions, the following general form:[14]
function name ($Param1, $Param2)
{
Instructions
}
The defined function is invoked in either of the following forms:[14]
name value1 value2
name -Param1 value1 -Param2 value2
PowerShell supports named parameters, positional parameters, switch parameters and dynamic parameters.[14]
PowerShell allows any .NET methods to be called by providing their namespaces enclosed in brackets ([]
), and then using a pair of colons (::
) to indicate the static method.[15] For example,
[System.Console]::WriteLine("PowerShell")
.
Objects are created using the New-Object
cmdlet. Calling methods of .NET objects is accomplished by using the regular .
notation.[15]
PowerShell scripting language accepts strings, both raw and escaped. A string enclosed between single quotation marks is a raw string while a string enclosed between double quotation marks is an escaped string. PowerShell treats straight and curly quotes as equivalent.[16]
For error handling, PowerShell provides a .NET-based exception handling mechanism. In case of errors, objects containing information about the error (Exception
object) are thrown, which are caught using the try ... catch
construct (although a trap
construct is supported as well). However, the action-or-error is configurable; in case of an error, PowerShell can be configured to silently resume execution, without actually throwing the exception.[17]
Scripts written using PowerShell can be made to persist across sessions in either a .ps1
file or a .psm1
file (the latter is used to implement a module). Later, either the entire script or individual functions in the script can be used. Scripts and functions are used analogously with cmdlets, in that they can be used as commands in pipelines, and parameters can be bound to them. Pipeline objects can be passed between functions, scripts, and cmdlets seamlessly. To prevent unintentional running of scripts, script execution is disabled by default and must be enabled explicitly.[18] Enabling of scripts can be performed either at system, user or session level. PowerShell scripts can be signed to verify their integrity, and are subject to Code Access Security.[19]
The PowerShell scripting language supports binary prefix notation similar to the scientific notation supported by many programming languages in the C-family.[citation needed]
Hosting
Another use of PowerShell is being embedded in a management application, which uses the PowerShell runtime to implement the management functionality. For this, PowerShell provides a managed hosting API. Via the APIs, the application can instantiate a runspace (one instantiation of the PowerShell runtime), which runs in the application's process and is exposed as a Runspace
object.[20] The state of the runspace is encased in a SessionState
object. When the runspace is created, the Windows PowerShell runtime initializes the instantiation, including initializing the providers and enumerating the cmdlets, and updates the SessionState
object accordingly. The Runspace then must be opened for either synchronous processing or asynchronous processing. After that it can be used to execute commands.
To execute a command, a pipeline (represented by a Pipeline
object) must be created and associated with the runspace. The pipeline object is then populated with the cmdlets that make up the pipeline. For sequential operations (as in a PowerShell script), a Pipeline object is created for each statement and nested inside another Pipeline object. When a pipeline is created, Windows PowerShell invokes the pipeline processor, which resolves the cmdlets into their respective assemblies (the command processor) and adds a reference to them to the pipeline, and associates them with InputPipe
, Outputpipe
and ErrorOutputPipe
objects, to represent the connection with the pipeline. The types are verified and parameters bound using reflection.[20] Once the pipeline is set up, the host calls the Invoke()
method to run the commands, or its asynchronous equivalent - InvokeAsync()
. If the pipeline has the Write-Host
cmdlet at the end of the pipeline, it writes the result onto the console screen. If not, the results are handed over to the host, which might either apply further processing or display it itself.
The hosting APIs are used by Microsoft Exchange Server 2007 to provide its management GUI. Each operation exposed in the GUI is mapped to a sequence of PowerShell commands (or pipelines). The host creates the pipeline and executes them. In fact, the interactive PowerShell console itself is a PowerShell host, which interprets the scripts entered at command line and creates the necessary Pipeline
objects and invokes them.
- ↑ about_Command_Precedence http://technet.microsoft.com/en-us/library/hh848304.aspx
- ↑ "Windows PowerShell Extended Type System". http://msdn2.microsoft.com/en-us/library/ms714419.aspx. Retrieved 2007-11-28.
- ↑ 3.0 3.1 3.2 "Windows PowerShell Cmdlets". http://msdn2.microsoft.com/en-us/library/ms714395.aspx. Retrieved 2007-11-28.
- ↑ "Creating Your First Cmdlet". http://msdn2.microsoft.com/en-us/library/ms714622.aspx. Retrieved 2007-11-28.
- ↑ Cmdlet OverView http://msdn.microsoft.com/en-us/library/windows/desktop/ms714395(v=vs.85).aspx
- ↑ Get-Verb http://technet.microsoft.com/en-us/library/hh852690.aspx
- ↑ "Adding parameters That Process Command Line Input". http://msdn2.microsoft.com/en-us/library/ms714663.aspx. Retrieved 2007-11-28.
- ↑ "Adding parameters That Process Pipeline Input". http://msdn2.microsoft.com/en-us/library/ms714597.aspx. Retrieved 2007-11-28.
- ↑ "Windows PowerShell Providers". http://technet.microsoft.com/en-us/library/dd347723.aspx. Retrieved 2010-10-14.
- ↑ "Anonymous Functions and Code Blocks in PowerShell". http://defndo.com/powershell-code-blocks-and-anonymous-functions/. Retrieved 2012-01-21.
- ↑ "Introduction to Windows PowerShell's Variables". http://www.computerperformance.co.uk/powershell/powershell_variables.htm. Retrieved 2007-11-28.
- ↑ "Byte Conversion". Windows PowerShell Tip of the Week. http://technet.microsoft.com/en-us/library/ee692684.aspx. Retrieved 15 November 2013.
- ↑ Ravikanth (20 May 2013). "Converting to size units (KB, MB,GB,TB, and PB) without using PowerShell multipliers". PowerShell Magazine. http://www.powershellmagazine.com/2013/05/20/converting-to-size-units-kb-mbgbtb-and-pb-without-using-powershell-multipliers/.
- ↑ 14.0 14.1 14.2 "about_Functions". Microsoft TechNet. Microsoft. 17 October 2013. http://technet.microsoft.com/en-us/library/hh847829.aspx. Retrieved 15 November 2013.
- ↑ 15.0 15.1 "Lightweight Testing with Windows PowerShell". http://msdn.microsoft.com/msdnmag/issues/07/05/TestRun/default.aspx. Retrieved 2007-11-28.
- ↑ Angelopoulos, Alex; Karen, Bemowski (4 December 2007). "PowerShell Got Smart About Smart Quotes". Windows IT Pro. Penton Media. http://windowsitpro.com/powershell/powershell-got-smart-about-smart-quotes. Retrieved 15 November 2013.
- ↑ "Trap [Exception] { “In PowerShell” }". http://huddledmasses.org/trap-exception-in-powershell. Retrieved 2007-11-28.
- ↑ "Running Windows PowerShell Scripts". http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/run.mspx. Retrieved 2007-11-28.
- ↑ "about_Signing". Microsoft TechNet. Microsoft. 17 October 2013. http://technet.microsoft.com/en-us/library/hh847874.aspx. Retrieved 15 November 2013.
- ↑ 20.0 20.1 Cite error: Invalid
<ref>
tag; no text was provided for refs namedhow