PowerShell


PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-source and cross-platform on 18 August 2016 with the introduction of PowerShell Core. The former is built on the.NET Framework, the latter on.NET Core.
In PowerShell, administrative tasks are generally performed by cmdlets, which are specialized.NET classes implementing a particular operation. These work by accessing data in different data stores, like the file system or registry, which are made available to PowerShell via providers. Third-party developers can add cmdlets and providers to PowerShell. Cmdlets may be used by scripts and scripts may be packaged into modules.
PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and CIM enabling management of remote Linux systems and network devices. PowerShell also provides a hosting API with which the PowerShell runtime can be embedded inside other applications. These applications can then use PowerShell functionality to implement certain operations, including those exposed via the graphical interface. This capability has been used by Microsoft Exchange Server 2007 to expose its management functionality as PowerShell cmdlets and providers and implement the graphical management tools as PowerShell hosts which invoke the necessary cmdlets. Other Microsoft applications including Microsoft SQL Server 2008 also expose their management interface via PowerShell cmdlets.
PowerShell includes its own extensive, console-based help accessible via the Get-Help cmdlet. Updated local help contents can be retrieved from the Internet via the Update-Help cmdlet. Alternatively, help from the web can be acquired on a case-by-case basis via the -online switch to Get-Help.

Background

Every version of Microsoft Windows for personal computers has included a command line interpreter for managing the operating system. Its predecessor, MS-DOS, relied exclusively on a CLI. These are COMMAND.COM in MS-DOS and Windows 9x, and cmd.exe in the Windows NT family of operating systems. Both support a few basic internal commands. For other purposes, a separate console application must be written. They also include a basic scripting language, which can be used to automate various tasks. However, they cannot be used to automate all facets of graphical user interface functionality, in part because command-line equivalents of operations are limited, and the scripting language is elementary. In Windows Server 2003, the situation was improved, but scripting support was still unsatisfactory.
Microsoft attempted to address some of these shortcomings by introducing the Windows Script Host in 1998 with Windows 98, and its command-line based host: cscript.exe. It integrates with the Active Script engine and allows scripts to be written in compatible languages, such as JScript and VBScript, leveraging the APIs exposed by applications via the component object model. However, it has its own deficiencies: its documentation is not very accessible, and it quickly gained a reputation as a system vulnerability vector after several high-profile computer viruses exploited weaknesses in its security provisions. Different versions of Windows provided various special-purpose command line interpreters with their own command sets but they were not interoperable.
In an interview published 2017 September 13, Jeffrey Snover explained the motivation for the project:

I'd been driving a bunch of managing changes, and then I originally took the UNIX tools and made them available on Windows, and then it just didn't work. Right? Because there's a core architectural difference between Windows and Linux. On Linux, everything's an ASCII text file, so anything that can manipulate that is a managing tool. AWK, grep, sed? Happy days!


I brought those tools available on Windows, and then they didn't help manage Windows because in Windows, everything's an API that returns structured data. So, that didn't help. I came up with this idea of PowerShell, and I said, "Hey, we can do this better."


By 2002, Microsoft had started to develop a new approach to command line management, including a CLI called Monad. The ideas behind it were published in August 2002 in a white paper titled Monad Manifesto. Monad was to be a new extensible CLI with a fresh design that would be capable of automating a full range of core administrative tasks. Microsoft first showed off Monad at the Professional Development Conference in Los Angeles in October 2003. A private beta program began a few months later which eventually led to a public beta program.
Microsoft published the first Monad public beta release on June 17, 2005, Beta 2 on September 11, 2005, and Beta 3 on January 10, 2006. Not much later, on April 25, 2006 Microsoft formally announced that Monad had been renamed Windows PowerShell, positioning it as a significant part of their management technology offerings. Release Candidate 1 of PowerShell was released at the same time. A significant aspect of both the name change and the RC was that this was now a component of Windows, and not an add-on product.
Release Candidate 2 of PowerShell version 1 was released on September 26, 2006 with final Release to the web on November 14, 2006 and announced at TechEd Barcelona. PowerShell for earlier versions of Windows was released on January 30, 2007.
PowerShell v2.0 development began before PowerShell v1.0 shipped. During the development, Microsoft shipped three community technology previews. Microsoft made these releases available to the public. The last CTP release of Windows PowerShell v2.0 was made available in December 2008.
PowerShell v2.0 was completed and released to manufacturing in August 2009, as an integral part of Windows 7 and Windows Server 2008 R2. Versions of PowerShell for Windows XP, Windows Server 2003, Windows Vista and Windows Server 2008 were released in October 2009 and are available for download for both 32-bit and 64-bit platforms.
Windows 10 shipped a testing framework for PowerShell.
On 18 August 2016, Microsoft announced that they had made PowerShell open-source and cross-platform with support for Windows, macOS, CentOS and Ubuntu. The source code was published on GitHub. The move to open source created a second incarnation of PowerShell called "PowerShell Core", which runs on.NET Core. It is distinct from "Windows PowerShell", which runs on the full.NET Framework. Starting with version 5.1, PowerShell Core is bundled with Windows Server 2016 Nano Server.

Design

PowerShell's developers based the core grammar of the tool on that of the POSIX 1003.2 Korn shell.
Windows PowerShell can execute four kinds of named commands:
If a command is a standalone executable program, PowerShell launches it in a separate process; if it is a cmdlet, it executes in the PowerShell process. PowerShell provides an interactive command-line interface, wherein the commands can be entered and their output displayed. The user interface offers customizable tab completion. PowerShell enables the creation of aliases for cmdlets, which PowerShell textually translates 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.
The PowerShell Extended Type System is based on the.NET type system, but with extended semantics. 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.

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. Cmdlets output their results as objects and can also receive objects as input, making them suitable for use as recipients in a pipeline. If a cmdlet outputs multiple objects, each object in the collection is passed down through the entire pipeline before the next object is processed.
Cmdlets are specialized.NET classes, which the PowerShell runtime instantiates and invokes at run-time. Cmdlets derive either from Cmdlet or from PSCmdlet, the latter being used when the cmdlet needs to interact with the PowerShell runtime. These base classes specify certain methods – BeginProcessing, ProcessRecord and EndProcessing – which the cmdlet's implementation overrides to provide the functionality. Whenever a cmdlet runs, PowerShell invokes these methods in sequence, with ProcessRecord being called if it receives pipeline input. 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 attributeCmdletAttribute – which specifies the verb and the noun that make up the name of the cmdlet. Common verbs are provided as an enum.
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 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.
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. 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, they can add specific providers as well.
PowerShell V2 added a more portable version of cmdlets called Modules. The PowerShell V2 release notes state:
The number of cmdlets has generally increased with each version:
VersionCmdlets
Windows PowerShell 1.0129
Windows PowerShell 2.0632
Windows PowerShell 3.0about 1,000
Windows PowerShell 4.0?
Windows PowerShell 5.0about 1,300
Windows PowerShell 5.11586
PowerShell Core 6.0?
PowerShell Core 6.1?
PowerShell Core 6.2?
PowerShell 7.01507

Pipeline

PowerShell implements the concept of a pipeline, which enables piping the output of one cmdlet to another cmdlet as input. For example, the output of the Get-Process cmdlet could be piped to the Where-Object to filter any process that has less than 1 MB of paged memory, and then to the Sort-Object cmdlet, and then finally to the Select-Object cmdlet to select just the first 10.
As with Unix pipelines, PowerShell pipelines can construct 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. For the last cmdlet in a pipeline, PowerShell automatically pipes its output object to the Out-Default cmdlet, which transforms the objects into a stream of format objects and then renders those to the screen.
Because all PowerShell objects are.NET objects, they share a .ToString method, which retrieves the text representation of the data in an object. In addition, PowerShell allows formatting definitions to be specified, so the text representation of objects can be customized by choosing which data elements to display, and in what manner. However, in order to maintain backwards compatibility, if an external executable is used in a pipeline, it receives a text stream representing the object, instead of directly integrating with the PowerShell type system.

Scripting

Windows PowerShell includes a dynamically typed scripting language which can implement complex operations using cmdlets imperatively. The scripting language supports variables, functions, branching, loops, structured error/exception handling and closures/lambda expressions, as well as integration with.NET. Variables in PowerShell scripts are prefixed with $. Variables 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 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.
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. 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.
Using the function keyword, PowerShell provides for the creation of functions, the following general form:
function name

The defined function is invoked in either of the following forms:

name value1 value2
name -Param1 value1 -Param2 value2

PowerShell supports named parameters, positional parameters, switch parameters and dynamic parameters.
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. For example,
::WriteLine.
Objects are created using the New-Object cmdlet. Calling methods of.NET objects is accomplished by using the regular . notation.
PowerShell 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.
The following list of special characters is supported by PowerShell:
CharacterDescription
`0Null
`aAlert
`bBackspace
`eEscape
`fForm feed
`nNewline
`rCarriage return
`tHorizontal tab
`uUnicode escape sequence
`vVertical tab
--%Stop parsing

For error handling, PowerShell provides a.NET-based exception-handling mechanism. In case of errors, objects containing information about the error are thrown, which are caught using the try... catch construct. PowerShell can be configured to silently resume execution, without actually throwing the exception; this can be done either on a single command, a single session or perpetually.
Scripts written using PowerShell can be made to persist across sessions in either a .ps1 file or a .psm1 file. Later, either the entire script or individual functions in the script can be used. Scripts and functions operate 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. 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.
The PowerShell scripting language supports binary prefix notation similar to the scientific notation supported by many programming languages in the C-family.

Hosting

One can also use PowerShell 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, which runs in the application's process and is exposed as a Runspace object. 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 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, 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 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. 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 the output itself.
Microsoft Exchange Server 2007 uses the hosting APIs to provide its management GUI. Each operation exposed in the GUI is mapped to a sequence of PowerShell commands. 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.

Desired State Configuration

DSC allows for declaratively specifying how a software environment should be configured.
Upon running a configuration, DSC will ensure that the system gets the state described in the configuration. DSC configurations are idempotent. The Local Configuration Manager periodically polls the system using the control flow described by resources to make sure that the state of a configuration is maintained.

Versions

Initially using the code name "Monad", PowerShell was first shown publicly at the Professional Developers Conference in September 2003. All major releases are still supported, and each major release has featured backwards compatibility with preceding versions.

Windows PowerShell 1.0

PowerShell 1.0 was released in November 2006 for Windows XP SP2, Windows Server 2003 SP1 and Windows Vista. It is an optional component of Windows Server 2008.

Windows PowerShell 2.0

PowerShell 2.0 is integrated with Windows 7 and Windows Server 2008 R2 and is released for Windows XP with Service Pack 3, Windows Server 2003 with Service Pack 2, and Windows Vista with Service Pack 1.
PowerShell v2 includes changes to the scripting language and hosting API, in addition to including more than 240 new cmdlets.
New features of PowerShell 2.0 include:
PowerShell 3.0 is integrated with Windows 8 and with Windows Server 2012. Microsoft has also made PowerShell 3.0 available for Windows 7 with Service Pack 1, for Windows Server 2008 with Service Pack 1, and for Windows Server 2008 R2 with Service Pack 1.
PowerShell 3.0 is part of a larger package, 3.0, which also contains the WinRM service to support remoting. Microsoft made several Community Technology Preview releases of WMF3. An early community technology preview 2 version of Windows Management Framework 3.0 was released on 2 December 2011. Windows Management Framework 3.0 was released for general availability in December 2012 and is included with Windows 8 and Windows Server 2012 by default.
New features in PowerShell 3.0 include:
PowerShell 4.0 is integrated with Windows 8.1 and with Windows Server 2012 R2. Microsoft has also made PowerShell 4.0 available for Windows 7 SP1, Windows Server 2008 R2 SP1 and Windows Server 2012.
New features in PowerShell 4.0 include:
Windows Management Framework 5.0 RTM which includes PowerShell 5.0 was re-released to web on February 24, 2016, following an initial release with a severe bug.
Key features include:
It was released along with the Windows 10 Anniversary Update on August 2, 2016, and in Windows Server 2016. PackageManagement now supports proxies, PSReadLine now has ViMode support, and two new cmdlets were added: Get-TimeZone and Set-TimeZone. The LocalAccounts module allows for adding/removing local user accounts. A preview for PowerShell 5.1 was released for Windows 7, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012, and Windows Server 2012 R2 on July 16, 2016, and was released on January 19, 2017.
PowerShell 5.1 is the first version to come in two editions of "Desktop" and "Core". The "Desktop" edition is the continuation of the traditional Windows PowerShell that runs on full.NET Framework stack. The "Core" edition runs on.NET Core and is bundled with Windows Server 2016 Nano Server. In exchange for smaller footprint, the latter lacks some features such as the cmdlets to manage clipboard or join a computer to a domain, WMI version 1 cmdlets, Event Log cmdlets and profiles. This was the final version of PowerShell made exclusively for Windows.

PowerShell Core 6

PowerShell Core 6.0 was first announced on 18 August 2016, when Microsoft unveiled PowerShell Core and its decision to make the product cross-platform, independent of Windows, free and open source. It achieved general availability on 10 January 2018 for Windows, macOS and Linux. It has its own support lifecycle and adheres to the Microsoft lifecycle policy that is introduced with Windows 10: Only the latest version of PowerShell Core is supported. Microsoft expects to release one minor version for PowerShell Core 6.0 every six months.
The most significant change in this version of PowerShell is the expansion to the other platforms. For Windows administrators, this version of PowerShell did not include any major new features. In an interview with the community on 11 January 2018, the PowerShell team was asked to list the top 10 most exciting things that would happen for a Windows IT professional who would migrate from Windows PowerShell 5.1 to PowerShell Core 6.0; in response, Angel Calvo of Microsoft could only name two: cross-platform and open-source.
According to Microsoft, one of the new features of PowerShell 6.1 is "Compatibility with 1900+ existing cmdlets in Windows 10 and Windows Server 2019." Still, no details of these cmdlets can be found it the full version of the change log. Microsoft later professes that this number was insufficient. as PowerShell Core failed to replace Windows PowerShell 5.1 and gain traction on Windows. It was, however, popular on Linux.
PowerShell Core 6.2 is focused primarily on performance improvements, bug fixes, and smaller cmdlet and language enhancements that improve the quality of life for users.

PowerShell 7

PowerShell 7 is the replacement product for PowerShell Core 6.x products as well as Windows PowerShell 5.1, which is the last supported Windows PowerShell version. In order for PowerShell 7 to be a viable replacement for Windows PowerShell 5.1 it must have near parity with Windows PowerShell in terms of compatibility with modules that ship with Windows.
New features in PowerShell 7 include:
The following table contains a selection of the cmdlets that ship with PowerShell, noting similar commands in other well-known command-line interpreters. Many of these similar commands come out-of-the-box defined as aliases within PowerShell, making it easy for people familiar with other common shells to start working.
PowerShell PowerShell Windows Command PromptUnix shellDescription
Get-ChildItemgci, dir, lsdirlsLists all files and folders in the current or given folder
Test-ConnectionpingpingpingSends ICMP echo requests to the specified machine from the current machine, or instructs another machine to do so
Get-Contentgc, type, cattypecatGets the content of a file
Get-Commandgcmhelptype, which, compgenLists available commands
Get-Helphelp, manhelpapropos, manPrints a command's documentation on the console
Clear-Hostcls, clearclsclearClears the screen
Copy-Itemcpi, copy, cpcopy, xcopy, robocopycpCopies files and folders to another location
Move-Itemmi, move, mvmovemvMoves files and folders to a new location
Remove-Itemri, del, erase, rmdir, rd, rmdel, erase, rmdir, rdrm, rmdirDeletes files or folders
Rename-Itemrni, ren, mvren, renamemvRenames a single file, folder, hard link or symbolic link
Get-Locationgl, cd, pwdcdpwdDisplays the working path
Pop-LocationpopdpopdpopdChanges the working path to the location most recently pushed onto the stack
Push-LocationpushdpushdpushdStores the working path onto the stack
Set-Locationsl, cd, chdircd, chdircdChanges the working path
Tee-ObjectteeteePipes input to a file or variable, passing the input along the pipeline
Write-Outputecho, writeechoechoPrints strings or other objects to the standard output
Get-Processgps, pstlist, tasklistpsLists all running processes
Stop-Processspps, killkill, taskkillkillStops a running process
Select-Stringslsfindstrfind, grepPrints lines matching a pattern
Set-Variablesv, setsetenv, export, set, setenvCreates or alters the contents of an environment variable
Invoke-WebRequestiwr, curl, wgetcurlwget, curlGets contents from a web page on the Internet

Notes

Filename extensions

Application support

ApplicationVersionCmdletsProviderManagement GUI
Exchange Server2007
Windows Server2008
Microsoft SQL Server2008
Microsoft SharePoint2010
System Center Configuration Manager2012 R2
System Center Operations Manager2007
System Center Virtual Machine Manager2007
System Center Data Protection Manager2007
Windows Compute Cluster Server2007
Microsoft Transporter Suite for Lotus Domino08.02.0012
Microsoft PowerTools for Open XML1.0
IBM WebSphere MQ6.0.2.2
IoT Core Add-ons
Quest Management Shell for Active Directory1.7
Special Operations Software Specops Command1.0
VMware vSphere PowerCLI6.5 R1
Internet Information Services7.0
Windows 7 Troubleshooting Center6.1
Microsoft Deployment Toolkit2010
NetApp PowerShell Toolkit4.2
JAMS Scheduler – Job Access & Management System5.0
UIAutomation0.8
Dell Equallogic3.5
LOGINventory5.8
SePSX0.4.1

Alternative implementation

A project named Pash has been an open source and cross-platform re-implementation of PowerShell via the Mono framework. Pash was created by Igor Moochnick, written in C# and was released under the GNU General Public License. Pash development stalled in 2008, was restarted on GitHub in 2012, and finally ceased in 2016 when PowerShell was officially made open-source and cross-platform.