Какие версии операционной системы windows поддерживают оболочку powershell

PowerShell

Screenshot of a PowerShell 7 session in Windows Terminal

Paradigm Imperative, pipeline, object-oriented, functional and reflective
Designed by Jeffrey Snover, Bruce Payette, James Truher (et al.)
Developer Microsoft
First appeared November 14, 2006; 16 years ago
Stable release

7.3.7
/ September 18, 2023; 21 days ago[1]

Preview release

v7.4.0-preview.6
/ September 28, 2023; 11 days ago[2]

Typing discipline Strong, safe, implicit and dynamic
Implementation language C#
Platform PowerShell: .NET
Windows PowerShell: .NET Framework
OS
  • Windows 7 and later
  • Windows Server 2008 R2 and later
  • macOS 10.12 and later
  • Ubuntu 14.04, 16.04, 18.04, 20.04 and 22.04
  • Debian 8.7+, 9, 10 and 11
  • CentOS 7 and 8
  • Red Hat Enterprise Linux 7 and 8
  • openSUSE 42.2, 42.3, 15.0, 15.1, 15.2
  • Fedora 28, 29, 30
License MIT License[3] (but the Windows component remains proprietary)
Filename extensions
  • .ps1 (Script)
  • .ps1xml (XML Document)
  • .psc1 (Console File)
  • .psd1 (Data File)
  • .psm1 (Script Module)
  • .pssc (Session Configuration File)
  • .psrc (Role Capability File)
  • .cdxml (Cmdlet Definition XML Document)
Website microsoft.com/powershell
Influenced by
Python, Ksh, Perl, C#, CL, DCL, SQL, Tcl, Tk,[4] Chef, Puppet

PowerShell is a task automation and configuration management program 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 August 18, 2016, with the introduction of PowerShell Core.[5] The former is built on the .NET Framework, the latter on .NET (previously .NET Core).

Since Windows 10 build 14971, PowerShell replaced Command Prompt and became the default command shell for File Explorer.[6][7]

In PowerShell, administrative tasks are generally performed via cmdlets (pronounced command-lets), which are specialized .NET classes implementing a particular operation. These work by accessing data in different data stores, like the file system or Windows Registry, which are made available to PowerShell via providers. Third-party developers can add cmdlets and providers to PowerShell.[8][9] Cmdlets may be used by scripts, which may in turn be packaged into modules. Cmdlets work in tandem with the .NET API.

PowerShell’s support for .NET Remoting, WS-Management, CIM, and SSH enables administrators to perform administrative tasks on both local and remote Windows systems. 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.[8][10] Other Microsoft applications including Microsoft SQL Server 2008 also expose their management interface via PowerShell cmdlets.[11]

PowerShell includes its own extensive, console-based help (similar to man pages in Unix shells) 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[edit]

The command-line interpreter (CLI) has been an inseparable part of most Microsoft operating systems. MS-DOS and Xenix relied almost exclusively on CLI. (MS-DOS 5 came with a complementary graphical DOS Shell.) The Windows 9x family came bundled with COMMAND.COM, the command-line environment of MS-DOS. The Windows NT and Windows CE families, however, came with a new cmd.exe that bore strong similarities to COMMAND.COM. Both environments support a few basic internal commands and a primitive scripting language (batch files), which can be used to automate various tasks. However, they cannot automate all facets of Windows graphical user interface (GUI) because command-line equivalents of operations are limited and the scripting language is elementary.

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 (COM). 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 (such as netsh and WMIC) with their own command sets but they were not interoperable. Windows Server 2003 further attempted to improve the command line experience but scripting support was still unsatisfactory.[12]

Kermit[edit]

By the late 1990s, Intel had come to Microsoft asking for help in making Windows, which ran on Intel CPUs, a more appropriate platform to support the development of future Intel CPUs. At the time, Intel CPU development was accomplished on Sun Microsystems computers which ran Solaris (a Unix variant) on RISC-architecture CPUs. The ability to run Intel’s many KornShell automation scripts on Windows was identified as a key capability. Internally, Microsoft began an effort to create a Windows port of Korn Shell, which was code-named Kermit.[13] Intel ultimately pivoted to a Linux-based development platform that could run on Intel CPUs, rendering the Kermit project redundant. However, with a fully funded team, Microsoft program manager Jeffrey Snover realized there was an opportunity to create a more general-purpose solution to Microsoft’s problem of administrative automation.

Monad[edit]

By 2002, Microsoft had started to develop a new approach to command-line management, including a CLI called Monad (also known as Microsoft Shell or MSH). The ideas behind it were published in August 2002 in a white paper called the «Monad Manifesto» by its chief architect, Jeffrey Snover.[14] In a 2017 interview, Snover explains the genesis of PowerShell, saying that he had been trying to make Unix tools available on Windows, which didn’t work due to «core architectural difference[s] between Windows and Linux». Specifically, he noted that Linux considers everything an ASCII text file, whereas Windows considers everything an «API that returns structured data». They were fundamentally incompatible, which led him to take a different approach.[15]

Monad was to be a new extensible CLI with a fresh design capable of automating a range of core administrative tasks. Microsoft first demonstrated Monad publicly at the Professional Development Conference in Los Angeles in October 2003. A few months later, they opened up private beta, which eventually led to a public beta. Microsoft published the first Monad public beta release on June 17, 2005, and the Beta 2 on September 11, 2005, and Beta 3 on January 10, 2006.

PowerShell[edit]

On April 25, 2006, not long after the initial Monad announcement, Microsoft announced that Monad had been renamed Windows PowerShell, positioning it as a significant part of its management technology offerings.[16] Release Candidate (RC) 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, rather than a mere add-on.

Release Candidate 2 of PowerShell version 1 was released on September 26, 2006, with final release to the web on November 14, 2006. PowerShell for earlier versions of Windows was released on January 30, 2007.[17] PowerShell v2.0 development began before PowerShell v1.0 shipped. During the development, Microsoft shipped three community technology previews (CTP). Microsoft made these releases available to the public. The last CTP release of Windows PowerShell v2.0 was made available in December 2008.

PowerShell for Linux 7.3.1 on Ubuntu 22.10

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.[18] In an October 2009 issue of TechNet Magazine, Microsoft called proficiency with PowerShell «the single most important skill a Windows administrator will need in the coming years».[19]

Windows 10 shipped a testing framework for PowerShell.[20]

On August 18, 2016, Microsoft announced[21] that they had made PowerShell open-source and cross-platform with support for Windows, macOS, CentOS and Ubuntu.[5] The source code was published on GitHub.[22] 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.[23] Starting with version 5.1, PowerShell Core is bundled with Windows Server 2016 Nano Server.[24][25]

Design[edit]

A key design tactic for PowerShell was to leverage the large number of APIs that already existed in Windows, Windows Management Instrumentation, .NET Framework, and other software. PowerShell cmdlets «wrap around» existing functionality. The intent with this tactic is to provide an administrator-friendly, more-consistent interface between administrators and a wide range of underlying functionality. With PowerShell, an administrator doesn’t need to know .NET, WMI, or low-level API coding, and can instead focus on using the cmdlets exposed by PowerShell. In this regard, PowerShell creates little new functionality, instead focusing on making existing functionality more accessible to a particular audience.[26]

Grammar[edit]

PowerShell’s developers based the core grammar of the tool on that of the POSIX 1003.2 KornShell.[27]

However, PowerShell’s language was also influenced by PHP, Perl, and many other existing languages.[28]

Named Commands[edit]

Windows PowerShell can execute four kinds of named commands:[29]

  • cmdlets (.NET Framework 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 launches it in a separate process; if it is a cmdlet, it executes in the PowerShell process. PowerShell provides an interactive command-line interface, where 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.[30]

Extended Type System[edit]

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.[31]

Cmdlets[edit]

Cmdlets are specialized commands in the PowerShell environment that implement specific functions. These are the native commands in the PowerShell stack. Cmdlets follow a VerbNoun naming pattern, such as Get-ChildItem, which makes it self-documenting code.[32] 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.[32]

Cmdlets are specialized .NET classes, which the PowerShell runtime instantiates and invokes at execution time. Cmdlets derive either from Cmdlet or from PSCmdlet, the latter being used when the cmdlet needs to interact with the PowerShell runtime.[32] 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.[33] 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.[34][35]

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[36] 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.[37]

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.[38] 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 a database), they can add specific providers as well.[citation needed]

The number of cmdlets included in the base PowerShell install has generally increased with each version:

Version Cmdlets
Windows PowerShell 1.0 129[39]
Windows PowerShell 2.0 632[40]
Windows PowerShell 3.0 about 1,000[41]
Windows PowerShell 4.0 ?
Windows PowerShell 5.0 about 1,300[42]
Windows PowerShell 5.1 1586[citation needed]
PowerShell Core 6.0 ?
PowerShell Core 6.1 ?
PowerShell Core 6.2 ?
PowerShell 7.0 1507[citation needed]
PowerShell 7.1 ?
PowerShell 7.2 ?

Cmdlets can be added into the shell through snap-ins (deprecated in v2) and modules; users are not limited to the cmdlets included in the base PowerShell installation.

Pipeline[edit]

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 (e.g., to sort the objects by handle count), and then finally to the Select-Object cmdlet to select just the first ten processes based on handle count.[citation needed]

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. Additionally, 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.[43] An object can also encapsulate certain functions that work on the contained data, which become available to the recipient command for use.[44][45] 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.[46][47]

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 backward 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.[48][49][50]

Scripting[edit]

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,[51] 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 (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.[52] 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.[53][54]

Using the function keyword, PowerShell provides for the creation of functions. A simple function has the following general look:[55]

function name ([Type]$Param1, [Type]$Param2) {
  # Instructions
}

However, PowerShell allows for advanced functions that support named parameters, positional parameters, switch parameters and dynamic parameters.[55]

function Verb-Noun {
  param (
    # Definition of static parameters
  )
  dynamicparam {
    # Definition of dynamic parameters
  }
  begin {
    # Set of instruction to run at the start of the pipeline
  }
  process {
    # Main instruction sets, ran for each item in the pipeline
  }
  end {
    # Set of instruction to run at the end of the pipeline
  }
}

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

name value1 value2
Verb-Noun -Param1 value1 -Param2 value2

PowerShell allows any static .NET methods to be called by providing their namespaces enclosed in brackets ([]), and then using a pair of colons (::) to indicate the static method.[56] For example:

[Console]::WriteLine("PowerShell")

There are dozens of ways to create objects in PowerShell. Once created, one can access the properties and instance methods of an object using the . notation.[56]

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.[57]

The following list of special characters is supported by PowerShell:[58]

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). 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.[59]

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 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.[60] 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.[61]

The PowerShell scripting language supports binary prefix notation similar to the scientific notation supported by many programming languages in the C-family.[62]

Hosting[edit]

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 (one instantiation of the PowerShell runtime), which runs in the application’s process and is exposed as a Runspace object.[8] 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.[citation needed]

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.[8] 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.[8] 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.[citation needed]

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 (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.[citation needed]

Desired State Configuration[edit]

DSC allows for declaratively specifying how a software environment should be configured.[63]

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 (LCM) periodically polls the system using the control flow described by resources (imperative pieces of DSC) to make sure that the state of a configuration is maintained.

Versions[edit]

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

Windows PowerShell 1.0[edit]

Windows PowerShell 1.0 session using the Windows Console

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

Windows PowerShell 2.0[edit]

Windows PowerShell ISE v2.0 on Windows 7, an integrated development environment for PowerShell scripts

PowerShell 2.0 is integrated with Windows 7 and Windows Server 2008 R2[65] and is released for Windows XP with Service Pack 3, Windows Server 2003 with Service Pack 2, and Windows Vista with Service Pack 1.[66][67]

PowerShell v2 includes changes to the scripting language and hosting API, in addition to including more than 240 new cmdlets.[68][69]

New features of PowerShell 2.0 include:[70][71][72]

  • PowerShell remoting: Using WS-Management, PowerShell 2.0 allows scripts and cmdlets to be invoked on a remote machine or a large set of remote machines.
  • Background jobs: Also called a PSJob, it allows a command sequence (script) or pipeline to be invoked asynchronously. Jobs can be run on the local machine or on multiple remote machines. An interactive cmdlet in a PSJob blocks the execution of the job until user input is provided.
  • Transactions: Enable cmdlet and developers can perform transactional operations. PowerShell 2.0 includes transaction cmdlets for starting, committing, and rolling back a PSTransaction as well as features to manage and direct the transaction to the participating cmdlet and provider operations. The PowerShell Registry provider supports transactions.
  • Advanced functions: These are cmdlets written using the PowerShell scripting language. Initially called «script cmdlets», this feature was later renamed «advanced functions».[73]
  • SteppablePipelines: This allows the user to control when the BeginProcessing(), ProcessRecord() and EndProcessing() functions of a cmdlet are called.
  • Modules: This allows script developers and administrators to organize and partition PowerShell scripts in self-contained, reusable units. Code from a module executes in its own self-contained context and does not affect the state outside the module. Modules can define a restricted runspace environment by using a script. They have a persistent state as well as public and private members.
  • Data language: A domain-specific subset of the PowerShell scripting language that allows data definitions to be decoupled from the scripts and allows localized string resources to be imported into the script at runtime (Script Internationalization).
  • Script debugging: It allows breakpoints to be set in a PowerShell script or function. Breakpoints can be set on lines, line & columns, commands and read or write access of variables. It includes a set of cmdlets to control the breakpoints via script.
  • Eventing: This feature allows listening, forwarding, and acting on management and system events. Eventing allows PowerShell hosts to be notified about state changes to their managed entities. It also enables PowerShell scripts to subscribe to ObjectEvents, PSEvents, and WmiEvents and process them synchronously and asynchronously.
  • Windows PowerShell Integrated Scripting Environment (ISE): PowerShell 2.0 includes a GUI-based PowerShell host that provides integrated debugger, syntax highlighting, tab completion and up to 8 PowerShell Unicode-enabled consoles (Runspaces) in a tabbed UI, as well as the ability to run only the selected parts in a script.
  • Network file transfer: Native support for prioritized, throttled, and asynchronous transfer of files between machines using the Background Intelligent Transfer Service (BITS).[74]
  • New cmdlets: Including Out-GridView, which displays tabular data in the WPF GridView object, on systems that allow it, and if ISE is installed and enabled.
  • New operators: -Split, -Join, and Splatting (@) operators.
  • Exception handling with Try-Catch-Finally: Unlike other .NET languages, this allows multiple exception types for a single catch block.
  • Nestable Here-Strings: PowerShell Here-Strings have been improved and can now nest.[75]
  • Block comments: PowerShell 2.0 supports block comments using <# and #> as delimiters.[76]
  • New APIs: The new APIs range from handing more control over the PowerShell parser and runtime to the host, to creating and managing collection of Runspaces (RunspacePools) as well as the ability to create Restricted Runspaces which only allow a configured subset of PowerShell to be invoked. The new APIs also support participation in a transaction managed by PowerShell

Windows PowerShell 3.0[edit]

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.[77][78]

PowerShell 3.0 is part of a larger package, Windows Management Framework 3.0 (WMF3), which also contains the WinRM service to support remoting.[78] Microsoft made several Community Technology Preview releases of WMF3. An early community technology preview 2 (CTP 2) version of Windows Management Framework 3.0 was released on December 2, 2011.[79] Windows Management Framework 3.0 was released for general availability in December 2012[80] and is included with Windows 8 and Windows Server 2012 by default.[81]

New features in PowerShell 3.0 include:[78][82]: 33–34 

  • Scheduled jobs: Jobs can be scheduled to run on a preset time and date using the Windows Task Scheduler infrastructure.
  • Session connectivity: Sessions can be disconnected and reconnected. Remote sessions have become more tolerant of temporary network failures.
  • Improved code writing: Code completion (IntelliSense) and snippets are added. PowerShell ISE allows users to use dialog boxes to fill in parameters for PowerShell cmdlets.
  • Delegation support: Administrative tasks can be delegated to users who do not have permissions for that type of task, without granting them perpetual additional permissions.
  • Help update: Help documentations can be updated via Update-Help command.
  • Automatic module detection: Modules are loaded implicitly whenever a command from that module is invoked. Code completion works for unloaded modules as well.
  • New commands: Dozens of new modules were added, including functionality to manage disks get-WmiObject win32_logicaldisk, volumes, firewalls, network connections, and printers, which had previously been performed via WMI.[further explanation needed]

Windows PowerShell 4.0[edit]

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.[83]

New features in PowerShell 4.0 include:

  • Desired State Configuration:[84][85][86] Declarative language extensions and tools that enable the deployment and management of configuration data for systems using the DMTF management standards and WS-Management Protocol
  • New default execution policy: On Windows Servers, the default execution policy is now RemoteSigned.
  • Save-Help: Help can now be saved for modules that are installed on remote computers.
  • Enhanced debugging: The debugger now supports debugging workflows, remote script execution and preserving debugging sessions across PowerShell session reconnections.
  • -PipelineVariable switch: A new ubiquitous parameter to expose the current pipeline object as a variable for programming purposes
  • Network diagnostics to manage physical and Hyper-V’s virtualized network switches
  • Where and ForEach method syntax provides an alternate method of filtering and iterating over objects.

Windows PowerShell 5.0[edit]

PowerShell 5.0 icon

Windows Management Framework (WMF) 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.[87]

Key features included:

  • The new class keyword that creates classes for object-oriented programming
  • The new enum keyword that creates enums
  • OneGet cmdlets to support the Chocolatey package manager[88]
  • Extending support for switch management to layer 2 network switches.[89]
  • Debugging for PowerShell background jobs and instances of PowerShell hosted in other processes (each of which is called a «runspace»)
  • Desired State Configuration (DSC) Local Configuration Manager (LCM) version 2.0
  • DSC partial configurations
  • DSC Local Configuration Manager meta-configurations
  • Authoring of DSC resources using PowerShell classes

Windows PowerShell 5.1[edit]

It was released along with the Windows 10 Anniversary Update[90] on August 2, 2016, and in Windows Server 2016.[91] 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.[92] 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,[93] and was released on January 19, 2017.[94]

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 the .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.[25] This was the final version of PowerShell made exclusively for Windows.

PowerShell Core 6[edit]

PowerShell Core 6.0 was first announced on August 18, 2016, when Microsoft unveiled PowerShell Core and its decision to make the product cross-platform, independent of Windows, free and open source.[5] It achieved general availability on January 10, 2018, for Windows, macOS and Linux.[95] 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.[96]

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 January 11, 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.[97]

6.1[edit]

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.»[98] Still, no details of these cmdlets can be found in the full version of the change log.[99] Microsoft later professes that this number was insufficient as PowerShell Core failed to replace Windows PowerShell 5.1 and gain traction on Windows.[100] It was, however, popular on Linux.[100]

6.2[edit]

PowerShell Core 6.2 is focused primarily on performance improvements, bug fixes, and smaller cmdlet and language enhancements that improved developer productivity.[101]

PowerShell 7[edit]

PowerShell 7 is the replacement for PowerShell Core 6.x products as well as Windows PowerShell 5.1, which is the last supported Windows PowerShell version.[102][100] The focus in development was to make PowerShell 7 a viable replacement for Windows PowerShell 5.1, i.e. to have near parity with Windows PowerShell in terms of compatibility with modules that ship with Windows.[103]

New features in PowerShell 7 include:[104]

  • The -Parallel switch for the ForEach-Object cmdlet to help handle parallel processing
  • Near parity with Windows PowerShell in terms of compatibility with built-in Windows modules
  • A new error view
  • The Get-Error cmdlet
  • Pipeline chaining operators (&& and ||) that allow conditional execution of the next cmdlet in the pipeline
  • The ?: operator for ternary operation
  • The ?? operator for null coalescing
  • The ??= operator for null coalescing assignment
  • Cross-platform Invoke-DscResource (experimental)
  • Return of the Out-GridView cmdlet
  • Return of the -ShowWindow switch for the Get-Help

PowerShell 7.2[edit]

PowerShell 7.2 is the next long-term support version of PowerShell, after version 7.0. It uses .NET 6.0 and features universal installer packages for Linux. On Windows, updates to PowerShell 7.2 and later come via the Microsoft Update service; this feature has been missing from PowerShell 6.0 through 7.1.[105]

PowerShell 7.3[edit]

This version includes some general Cmdlet updates and fixes, testing for framework dependent package in release pipeline as well as build and packaging improvements.[106]

PowerShell 7.4[edit]

[icon]

This section is empty. You can help by adding to it. (April 2023)

Comparison of cmdlets with similar commands[edit]

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.

Notes

  1. ^ a b ls and man aliases are absent in the Linux version of PowerShell Core.
  2. ^ While the external ping command remains available to PowerShell, Test-Connection’s output is a structured object that can be programmatically inspected.[107]
  3. ^ Clear-Host is implemented as a predefined PowerShell function.
  4. ^ a b Available in Windows NT 4, Windows 98 Resource Kit, Windows 2000 Support Tools
  5. ^ a b Introduced in Windows XP Professional Edition
  6. ^ Also used in UNIX to send a process any signal, the «Terminate» signal is merely the default
  7. ^ curl and wget aliases are absent from PowerShell Core, so as to not interfere with invoking similarly named native commands.

Filename extensions[edit]

Extension Description
.ps1 Script file[109]
.psd1 Module’s manifest file; usually comes with a script module or binary module[110]
.psm1 Script module file[111]
.dll DLL-compliant[a] binary module file[112]
.ps1xml Format and type definitions file[50][113]
.xml XML-compliant[b] serialized data file[114]
.psc1 Console file[115]
.pssc Session configuration file[116]
.psrc Role Capability file[117]
  1. ^ Dynamic-link library (DLL) is not a PowerShell-only format. It is a generic format for storing compiled .NET assembly’s code.
  2. ^ XML is not a PowerShell-only format. It is a popular information interchange format.

Application support[edit]

Application Version Cmdlets Provider Management GUI
Exchange Server 2007 402 Yes Yes
Windows Server 2008 Yes Yes No
Microsoft SQL Server 2008 Yes Yes No
Microsoft SharePoint 2010 Yes Yes No
System Center Configuration Manager 2012 R2 400+ Yes No
System Center Operations Manager 2007 74 Yes No
System Center Virtual Machine Manager 2007 Yes Yes Yes
System Center Data Protection Manager 2007 Yes No No
Windows Compute Cluster Server 2007 Yes Yes No
Microsoft Transporter Suite for Lotus Domino[118] 08.02.0012 47 No No
Microsoft PowerTools for Open XML[119] 1.0 33 No No
IBM WebSphere MQ[120] 6.0.2.2 44 No No
IoT Core Add-ons[121] 74 Un­known Un­known
Quest Management Shell for Active Directory[122] 1.7 95 No No
Special Operations Software Specops Command[123] 1.0 Yes No Yes
VMware vSphere PowerCLI[124] 6.5 R1 500+ Yes Yes
Internet Information Services[125] 7.0 54 Yes No
Windows 7 Troubleshooting Center[126] 6.1 Yes No Yes
Microsoft Deployment Toolkit[127] 2010 Yes Yes Yes
NetApp PowerShell Toolkit[128][129] 4.2 2000+ Yes Yes
JAMS Scheduler – Job Access & Management System[130] 5.0 52 Yes Yes
UIAutomation[131] 0.8 432 No No
Dell Equallogic[132] 3.5 55 No No
LOGINventory[133] 5.8 Yes Yes Yes
SePSX[134] 0.4.1 39 No No

Alternative implementation[edit]

A project named Pash, a pun on the widely known «bash» Unix shell, has been an open-source and cross-platform reimplementation of PowerShell via the Mono framework.[135] 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,[136] and finally ceased in 2016 when PowerShell was officially made open-source and cross-platform.[137]

See also[edit]

  • Common Information Model (computing)
  • Comparison of command shells
  • Comparison of programming languages
  • Web-Based Enterprise Management
  • Windows Script Host
  • Windows Terminal

References[edit]

  1. ^ «v7.3.7 Release of PowerShell». PowerShell/PowerShell repo. Microsoft. Retrieved October 6, 2023 – via GitHub.com.
  2. ^ «v7.4.0-preview.6 Release of PowerShell». PowerShell/PowerShell repo. Microsoft. Retrieved October 6, 2023 – via GitHub.com.
  3. ^ «PowerShell for every system!». June 12, 2017 – via GitHub.com.
  4. ^ Snover, Jeffrey (May 25, 2008). «PowerShell and WPF: WTF». Windows PowerShell Blog. Microsoft.
  5. ^ a b c Bright, Peter (August 18, 2016). «PowerShell is Microsoft’s latest open source release, coming to Linux, OS X». Ars Technica. Condé Nast. Archived from the original on April 9, 2020. Retrieved May 12, 2020.
  6. ^ «Announcing Windows 10 Insider Preview Build 14971 for PC».
  7. ^ «PowerShell is replacing Command Prompt».
  8. ^ a b c d e «powershell». Retrieved March 13, 2023.
  9. ^ Truher, Jim (December 2007). «Extend Windows PowerShell With Custom Commands». MSDN Magazine. Microsoft. Archived from the original on October 6, 2008.
  10. ^ Lowe, Scott (January 4, 2007). «Exchange 2007: Get used to the command line». TechRepublic. CBS Interactive. Archived from the original on November 16, 2018. Retrieved May 12, 2020.
  11. ^ Snover, Jeffrey (November 13, 2007). «SQL Server Support for PowerShell!». Windows PowerShell Blog (blog posting). Microsoft. Archived from the original on November 15, 2007. Retrieved November 13, 2007.
  12. ^ Dragan, Richard V. (April 23, 2003). «Windows Server 2003 Delivers Improvements All Around». PCMag.com. Ziff Davis. A standout feature here is that virtually all admin utilities now work from the command line (and most are available through telnet).
  13. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Don Gannon-Jones. p. 25. ISBN 978-1-9536450-3-6.
  14. ^ Jeffrey P. Snover (August 8, 2002). «Monad Manifesto» (PDF). Windows PowerShell Blog. Microsoft. Retrieved April 2, 2021.
  15. ^ Biggar and Harbaugh (September 14, 2017). «The Man Behind Windows PowerShell». To Be Continuous (Podcast). Heavybit. Retrieved September 14, 2017.
  16. ^ «Windows PowerShell (Monad) Has Arrived». Windows PowerShell Blog. Microsoft. April 25, 2006.
  17. ^ Snover, Jeffrey (November 15, 2006). «Windows PowerShell & Windows Vista». Windows PowerShell Blog (blog posting). Microsoft.
  18. ^ «Windows Management Framework (Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0)». Support. Microsoft. September 30, 2013. Archived from the original on October 13, 2013.
  19. ^ Posey, Brien (October 6, 2009). «10 reasons why you should learn to use PowerShell». TechRepublic. Retrieved April 2, 2021.
  20. ^ «What is Pester and Why Should I Care?». December 14, 2015.
  21. ^ Snover, Jeffrey (August 18, 2016). «PowerShell is open sourced and is available on Linux». Microsoft Azure Blog. Microsoft.
  22. ^ «PowerShell/PowerShell». GitHub. Retrieved August 18, 2016.
  23. ^ Hansen, Kenneth; Calvo, Angel (August 18, 2016). «PowerShell on Linux and Open Source!». Windows PowerShell Blog. Microsoft.
  24. ^ Foley, Mary Jo (August 18, 2016). «Microsoft open sources PowerShell; brings it to Linux and Mac OS X». ZDNet. CBS Interactive.
  25. ^ a b «PowerShell on Nano Server». TechNet. Microsoft. October 20, 2016.
  26. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Don Gannon-Jones. p. 45. ISBN 978-1-9536450-3-6.
  27. ^
    Payette, Bruce (2007). Windows PowerShell in Action. Manning Pubs Co Series. Manning. p. 27. ISBN 9781932394900. Retrieved July 22, 2016. The core PowerShell language is based on the POSIX 1003.2 grammar for the Korn shell.
  28. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Don Gannon-Jones. p. 109. ISBN 978-1-9536450-3-6.
  29. ^ «about_Command_Precedence». TechNet. Microsoft. May 8, 2014.
  30. ^ Wheeler, Sean (September 7, 2021). «about Parsing — PowerShell». Microsoft Docs. Retrieved December 5, 2021.
  31. ^ «Windows PowerShell Extended Type System». Retrieved November 28, 2007.
  32. ^ a b c «Windows PowerShell Cmdlets». Retrieved November 28, 2007.
  33. ^ «Creating Your First Cmdlet». Retrieved November 28, 2007.
  34. ^ «Get-Verb». TechNet. Microsoft. May 8, 2014.
  35. ^ «Cmdlet Overview». MSDN. Microsoft. May 8, 2014.
  36. ^ «Adding parameters That Process Command Line Input». Retrieved November 28, 2007.
  37. ^ «Adding parameters That Process Pipeline Input». Retrieved November 28, 2007.
  38. ^ «Windows PowerShell Providers». Retrieved October 14, 2010.
  39. ^ Yoshizawa, Tomoaki; Ramos, Durval (September 29, 2012). «PowerShell 1.0 Cmdlets». TechNet Articles. Microsoft.
  40. ^ Yoshizawa, Tomoaki (July 10, 2012). «PowerShell 2.0 Cmdlets». TechNet Articles. Microsoft.
  41. ^ Wilson, Ed (2013). «1: Overview of Windows PowerShell 3.0». Windows Powershell 3.0 Step by Step. Sebastopol, California: Microsoft Press. ISBN 978-0-7356-7000-6. OCLC 829236530. Windows PowerShell 3.0 comes with about 1,000 cmdlets on Windows 8
  42. ^ Wilson, Ed (2015). «1: Overview of Windows PowerShell 5.0». Windows PowerShell Step by Step (Third ed.). Redmond, Washington: Microsoft Press. ISBN 978-1-5093-0043-3. OCLC 927112976. Windows PowerShell 5.0 comes with about 1,300 cmdlets on Windows 10
  43. ^ «Windows PowerShell Owner’s Manual: Piping and the Pipeline in Windows PowerShell». TechNet. Microsoft. Retrieved September 27, 2011.
  44. ^ Jones, Don (2008). «Windows PowerShell – Rethinking the Pipeline». Microsoft TechNet. Microsoft. Retrieved November 28, 2007.
  45. ^ «Windows PowerShell Object Concepts». Archived from the original on August 19, 2007. Retrieved November 28, 2007.
  46. ^ «How PowerShell Formatting and Outputting REALLY works». Retrieved November 28, 2007.
  47. ^ «More – How does PowerShell formatting really work?». Retrieved November 28, 2007.
  48. ^ «about_Pipelines». TechNet. Microsoft. May 8, 2014.
  49. ^ «about_Objects». TechNet. Microsoft. May 8, 2014.
  50. ^ a b «about_Format.ps1xml». TechNet. Microsoft. May 8, 2014.
  51. ^ «Anonymous Functions and Code Blocks in PowerShell». Retrieved January 21, 2012.
  52. ^ «Introduction to Windows PowerShell’s Variables». Retrieved November 28, 2007.
  53. ^ «Byte Conversion». Windows PowerShell Tip of the Week. Retrieved November 15, 2013.
  54. ^ Ravikanth (May 20, 2013). «Converting to size units (KB, MB, GB, TB, and PB) without using PowerShell multipliers». PowerShell Magazine.
  55. ^ a b c «about_Functions». Microsoft TechNet. Microsoft. October 17, 2013. Retrieved November 15, 2013.
  56. ^ a b «Lightweight Testing with Windows PowerShell». Retrieved November 28, 2007.
  57. ^ Angelopoulos, Alex; Karen, Bemowski (December 4, 2007). «PowerShell Got Smart About Smart Quotes». Windows IT Pro. Penton Media. Retrieved November 15, 2013.
  58. ^ «About Special Characters». Powershell / Scripting. Microsoft. June 8, 2017. Retrieved June 20, 2019.
  59. ^ «Trap [Exception] { «In PowerShell» }». Retrieved November 28, 2007.
  60. ^ «Running Windows PowerShell Scripts». Microsoft. Retrieved November 28, 2007.
  61. ^ «about_Signing». Microsoft TechNet. Microsoft. October 17, 2013. Retrieved November 15, 2013.
  62. ^ Lee Holmes (September 2006). Windows PowerShell Quick Reference. O’Reilly Media.
  63. ^ eslesar (May 23, 2023). «Windows PowerShell Desired State Configuration Overview». msdn.microsoft.com.
  64. ^ Chung, Leonard; Snover, Jeffrey; Kumaravel, Arul (November 14, 2006). «It’s a Wrap! Windows PowerShell 1.0 Released!». Windows PowerShell Blog. Microsoft.
  65. ^ «PowerShell will be installed by default on Windows Server 08 R2 (WS08R2) and Windows 7 (W7)!». Windows PowerShell Blog. Microsoft. October 28, 2008. Retrieved September 27, 2011.
  66. ^ «Windows Management Framework is here!». October 27, 2009. Retrieved October 30, 2009.
  67. ^ «Microsoft Support Knowledge Base: Windows Management Framework (Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0)». Support.microsoft.com. September 23, 2011. Retrieved September 27, 2011.
  68. ^ «574 Reasons Why We Are So Proud and Optimistic About W7 and WS08R2». Windows PowerShell Blog. Microsoft. October 29, 2008. Retrieved September 27, 2011.
  69. ^ Snover, Jeffrey (2008). «PowerShell: Creating Manageable Web Services». Archived from the original on October 13, 2008. Retrieved July 19, 2015.
  70. ^ «What’s New in CTP of PowerShell 2.0». Retrieved November 28, 2007.
  71. ^ «Windows PowerShell V2 Community Technology Preview 2 (CTP2) – releaseNotes». Microsoft. Archived from the original on May 6, 2008. Retrieved May 5, 2008.
  72. ^ «Differences between PowerShell 1.0 and PowerShell 2.0». Archived from the original on September 17, 2010. Retrieved June 26, 2010.
  73. ^ Jones, Don (May 2010). «Windows PowerShell: Writing Cmdlets in Script». TechNet Magazine. Microsoft.
  74. ^ «GoGrid Snap-in – Managing Cloud Services with PowerShell». Windows PowerShell Blog. Microsoft. October 14, 2008. Retrieved September 27, 2011.
  75. ^ «Emit-XML». Windows PowerShell Blog. Microsoft. October 17, 2008. Retrieved September 27, 2011.
  76. ^ «Block Comments in V2». Windows PowerShell Blog. Microsoft. June 14, 2008. Retrieved September 27, 2011.
  77. ^ Lee, Thomas (August 13, 2012). «PowerShell Version 3 is RTM!». Under The Stairs. Retrieved August 13, 2012.
  78. ^ a b c «Windows Management Framework 3.0». Download Center. Microsoft. September 4, 2012. Retrieved November 8, 2012.
  79. ^ «Windows Management Framework 3.0 Community Technology Preview (CTP) #2 Available for Download». Windows PowerShell Blog. Microsoft. December 2, 2011.
  80. ^ «Windows Management Framework 3.0». Download Center. Microsoft. December 3, 2012.
  81. ^ Jofre, JuanPablo (December 14, 2016). «Windows PowerShell System Requirements». Microsoft Developer Network. Microsoft. Retrieved April 20, 2017.
  82. ^ Honeycutt, Jerry (2012). Woolley, Valerie (ed.). Introducing Windows 8: An Overview for IT Professionals. Redmond, WA: Microsoft Press. ISBN 978-0-7356-7050-1.
  83. ^ «Windows Management Framework 4.0 is now available». Microsoft. October 24, 2013. Retrieved November 4, 2013.
  84. ^ Levy, Shay (June 25, 2013). «New Features in Windows PowerShell 4.0». PowerShell Magazine. Retrieved June 26, 2013.
  85. ^ «Desired State Configuration in Windows Server 2012 R2 PowerShell». Channel 9. Microsoft. June 3, 2013. Archived from the original on December 26, 2013. Retrieved June 26, 2013.
  86. ^ Hall, Adrian (June 7, 2013). «Thoughts from Microsoft TechEd North America». Blogs: Tips & Tricks. Splunk. Retrieved June 26, 2013.
  87. ^ «Windows Management Framework (WMF) 5.0 RTM packages has been republished». Windows PowerShell Blog. Microsoft. February 24, 2016.
  88. ^ «Q and A». GitHub. Retrieved April 21, 2015.
  89. ^ Snover, Jeffrey (April 3, 2014). «Windows Management Framework V5 Preview». blogs.technet.com. Microsoft. Archived from the original on June 30, 2014. Retrieved April 21, 2015.
  90. ^ says, Jaap Brasser (August 2, 2016). «#PSTip New PowerShell Commands in Windows 10 Anniversary Update».
  91. ^ «What’s New In Windows Server 2016 Standard Edition Part 9 – Management And Automation». September 4, 2016.
  92. ^ «Microsoft.PowerShell.LocalAccounts Module». technet.microsoft.com. June 16, 2016.
  93. ^ «Announcing Windows Management Framework (WMF) 5.1 Preview». July 16, 2016.
  94. ^ «WMF 5.1». Microsoft Download Center.
  95. ^ Aiello, Joey (January 11, 2018). «PowerShell Core 6.0: Generally Available (GA) and Supported!». PowerShell Team Blog. Microsoft. Archived from the original on June 11, 2018. Retrieved June 11, 2018.
  96. ^ Aiello, Joey; Wheeler, Sean (January 10, 2018). «PowerShell Core Support Lifecycle». Microsoft Docs. Microsoft.
  97. ^ Calvo, Angel (January 11, 2018). «Top 10 most exciting reasons to migrate». PowerShell AMA. Microsoft.
  98. ^ Aiello, Joey (September 13, 2018). «Announcing PowerShell Core 6.1». devblogs.microsoft.com. Microsoft. Retrieved June 1, 2019.
  99. ^ «PowerShell/PowerShell». GitHub. Retrieved June 22, 2020.
  100. ^ a b c Lee, Steve (April 5, 2019). «The Next Release of PowerShell – PowerShell 7». Microsoft. Retrieved June 1, 2019.
  101. ^ Lee, Steve (March 28, 2019). «General Availability of PowerShell Core 6.2». devblogs.microsoft.com. Microsoft. Retrieved June 1, 2019.
  102. ^ Mackie, Kurt (May 30, 2019). «Microsoft Releases PowerShell 7 Preview». 1105 Media Inc. Retrieved June 1, 2019.
  103. ^ Lee, Steve (May 30, 2019). «PowerShell 7 Road Map». devblogs.microsoft.com. Microsoft. Retrieved August 12, 2020.
  104. ^ «PowerShell 7 Preview 5 | PowerShell». October 23, 2019. Archived from the original on February 15, 2020. Retrieved March 5, 2020.
  105. ^ «PowerShell 7.2 is the new version of Microsoft’s next-generation shell». itsfoss.net. November 12, 2021.
  106. ^ «Release v7.3.0 Release of PowerShell · PowerShell/PowerShell». GitHub. Archived from the original on November 9, 2022. Retrieved March 7, 2022.
  107. ^ «Test-Connection». PowerShell documentations. Microsoft. August 9, 2015.
  108. ^ «Tar and Curl Come to Windows! — Microsoft Tech Community — 382409». March 22, 2019. Archived from the original on September 11, 2020. Retrieved May 17, 2020.
  109. ^ Wheeler, Sean (June 2, 2020). «About Scripts». Microsoft Docs. Microsoft.
  110. ^ Wheeler, Sean; Smatlak, David; Wilson, Chase (October 16, 2019). «How to write a PowerShell module manifest». Docs. Microsoft.
  111. ^ Wheeler, Sean; Smatlak, David (November 22, 2019). «How to Write a PowerShell Script Module». Microsoft Docs. Microsoft.
  112. ^ Wheeler, Sean (November 13, 2016). «How to Write a PowerShell Binary Module». Microsoft Docs. Microsoft.
  113. ^ Wheeler, Sean; Jofre, Juan Pablo; Vorobev, Sergei; Nikolaev, Kirill; Coulter, David (June 2, 2020). «About Types.ps1xml». Microsoft Docs. Microsoft.
  114. ^ Wheeler, Sean. «Export-Clixml». Microsoft Docs. Microsoft.
  115. ^ Wheeler, Sean; Jofre, Juan Pablo; Vorobev, Sergei; Nikolaev, Kirill; Coulter, David. «Export-Console». Microsoft Docs. Microsoft.
  116. ^ Wheeler, Sean (June 2, 2020). «About Session Configuration Files». Microsoft Docs. Microsoft.
  117. ^ Wheeler, Sean (June 2, 2020). «New-PSRoleCapabilityFile». Microsoft Docs. Microsoft.
  118. ^ «Microsoft Transporter Suite for Lotus Domino». Microsoft. Retrieved March 7, 2008.
  119. ^ «PowerTools for Open XML». Retrieved June 20, 2008.
  120. ^ «MO74: WebSphere MQ – Windows PowerShell Library». Retrieved December 5, 2007.
  121. ^ «IoT Core Add-ons command-line options». Retrieved June 13, 2020.
  122. ^ «PowerShell Commands for Active Directory by Quest Software». Retrieved July 2, 2008.
  123. ^ «PowerShell Remoting through Group Policy». Retrieved December 7, 2007.
  124. ^ «VMware vSphere PowerCLI». Archived from the original on December 30, 2014. Retrieved September 9, 2014.
  125. ^ «Windows PowerShell : IIS7 PowerShell Provider Tech Preview 2». Retrieved July 3, 2008.
  126. ^ «Kudos to the Win7 Diagnostics Team». Retrieved June 15, 2009.
  127. ^ Michael, Niehaus (July 10, 2009). «MDT 2010 New Feature #16: PowerShell support». Retrieved October 27, 2014.
  128. ^ «Kudos to NetApp for Data ONTAP PowerShell ToolKit». Retrieved June 15, 2010.
  129. ^ «PowerShell Toolkit 4.2 Announcement». June 23, 2016. Retrieved September 7, 2016.
  130. ^ «Heterogeneous Job Scheduling With PowerShell». Retrieved September 15, 2010.
  131. ^ «UIAutomation PowerShell Extensions». Archived from the original on August 17, 2016. Retrieved February 16, 2012.
  132. ^ «EqualLogic HIT-ME with PowerShell». Retrieved March 9, 2012.
  133. ^ de:LOGINventory
  134. ^ «Selenium PowerShell eXtensions». Archived from the original on January 19, 2013. Retrieved August 20, 2012.
  135. ^ «Pash». SourceForge. Dice Holdings, Inc. Retrieved September 27, 2011.
  136. ^ «Pash Project». GitHub. Retrieved April 10, 2013.
  137. ^ «Pash is now obsolete · Issue #429 · Pash-Project/Pash». GitHub. Retrieved November 26, 2019.

Further reading[edit]

  • Finke, Douglas (2012). Windows PowerShell for Developers. O’Reilly Media. ISBN 978-1-4493-2270-0.
  • Holmes, Lee (2006). Windows PowerShell Quick Reference. O’Reilly Media. ISBN 0-596-52813-2.
  • Holmes, Lee (2007). Windows PowerShell Cookbook. O’Reilly Media. ISBN 978-0-596-52849-2.
  • Jones, Don; Hicks, Jeffery (2010). Windows PowerShell 2.0: TFM (3rd ed.). Sapien Technologies. ISBN 978-0-9821314-2-8.
  • Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Self-published. ISBN 978-1-9536450-3-6.
  • Kopczynski, Tyson; Handley, Pete; Shaw, Marco (2009). Windows PowerShell Unleashed (2nd ed.). Pearson Education. ISBN 978-0-672-32988-3.
  • Kumaravel, Arul; White, Jon; Naixin Li, Michael; Happell, Scott; Xie, Guohui; Vutukuri, Krishna C. (2008). Professional Windows PowerShell Programming: Snapins, Cmdlets, Hosts and Providers. Wrox Press. ISBN 978-0-470-17393-0.
  • Oakley, Andy (2005). Monad (AKA PowerShell). O’Reilly Media. ISBN 0-596-10009-4.
  • Watt, Andrew (2007). Professional Windows PowerShell. Wrox Press. ISBN 978-0-471-94693-9.
  • Wilson, Ed (2013). Windows PowerShell 3.0 Step by Step. Microsoft Press. ISBN 978-0-7356-6339-8.
  • Wilson, Ed (2014). Windows PowerShell Best Practices. Microsoft Press. ISBN 978-0-7356-6649-8.

External links[edit]

Wikiversity has learning resources about PowerShell

  • Official website Edit this at Wikidata
  • PowerShell on GitHub
  • Windows PowerShell Survival Guide on TechNet Wiki

В данной статье мы рассмотрим такую технологию от компании Microsoft как Windows PowerShell, мы поговорим о том, что такое PowerShell, что такое командлеты и конвейер, как писать сценарии и модули, а также затронем другие не менее важные и полезные возможности Windows PowerShell.

Основы Windows PowerShell для начинающих

Содержание

  1. Что способствовало появлению Windows PowerShell?
  2. Что такое Windows PowerShell?
  3. Версии Windows PowerShell
  4. Язык PowerShell
  5. Оболочка Windows PowerShell
  6. Командлеты в PowerShell
  7. Конвейер в PowerShell
  8. Фоновое исполнение заданий
  9. Удаленное управление на PowerShell
  10. Сценарии, функции и модули в Windows PowerShell
  11. Интегрированная среда сценариев Windows PowerShell (ISE)

До появления PowerShell существовали (и существуют) следующие инструменты для автоматизации и администрирования сервисов: командная строка Windows и Windows Script Host. Но у этих технологий есть недостатки.

У командной строки Windows есть и возможность выполнять какие-то административные задачи и возможность записать алгоритм действий, сохранив его в виде скрипта (bat-файла), при этом можно использовать некие элементы программирования, например, использовать переменные, условные конструкции и даже что-то вроде циклов.

Большинство программных продуктов имеет консольный интерфейс, т.е. мы можем управлять программой, используя командную строку, при этом экономя ресурсы за счет отсутствия затрат на работу графического интерфейса. Компания Microsoft для серверной операционной системы Windows Server даже выпускает редакции без графического интерфейса (Server Core, в Windows Server 2019), но всего этого недостаточно, так как возможности командной строки ограничены, т.е. написать какую-то сложную логику для автоматизации чего-либо мы не сможем, а если и сможем, то на это нам потребуется время и знания.

Также недостатком командной строки является то, что для полноценного управления сервером мы используем различные консольные утилиты программных продуктов, и поэтому использовать командную строку для администрирования на самом деле сложно, с точки зрения того, что у всех этих утилит разный синтаксис, параметры, методы использования и для того чтобы выполнять типовые задачи, т.е. каждодневные, приходиться держать все это в памяти, а для выполнения нетиповых задач приходиться сначала почитать справку или документацию.

Технология Windows Script Host позволяет выполнять все административные задачи, что и командная строка, включая их автоматизацию путем написания WSH скриптов, но здесь мы уже можем использовать полноценные языки программирования (VBScript и JScript), т.е. можно реализовывать сложную логику и алгоритмы. К тому же с помощью WSH мы управляем программными продуктами через объектный интерфейс, другими словами Windows Script Host намного «круче» чем командная строка. Но данная технология также не стала тем идеальным инструментом администрирования и автоматизации этого администрирования для системных администраторов, так как Windows Script Host требовал знаний вышеперечисленных языков программирования, что для системных администраторов на самом деле лишнее. Администраторам нужно всего лишь простой инструмент администрирования с возможностью запрограммировать какие-то действия, а углубляться в объектные модели программных продуктов на языках программирования VBScript и JScript им не хочется.

В итоге компании Microsoft необходимо было разработать такой инструмент администрирования для системных администраторов, который бы на 100 процентов удовлетворял все потребности сисадминов как в плане возможностей администрирования и автоматизации, так и в плане удобства и простоты использования, таким образом, появился Windows PowerShell.

Заметка! Курсы по SQL для начинающих на примере Microsoft SQL Server.

Скриншот 1

Windows PowerShell – это язык сценариев и командная оболочка Windows, которые разработаны для администрирования и конфигурирования операционных систем Windows.

PowerShell разработан на основе среды CRL и платформы .NET Framework и в отличие от командной строки, которая принимает и возвращает текст, Windows PowerShell работает с объектами. У каждого объекта в PowerShell есть свойства и методы, которые можно использовать для управления этими объектами.

В Windows PowerShell Microsoft разработала концепцию командлетов (cmdlets), которая представляет собой систему именования команд «Глагол-Существительное». Данная система позволяет системным администраторам быстрей освоить и упростить работу с PowerShell.

С помощью Windows PowerShell можно:

  • Получать доступ к файловой системе;
  • Управлять реестром;
  • Управлять службами;
  • Управлять процессами;
  • Настраивать операционную систему;
  • Устанавливать программное обеспечение;
  • Устанавливать роли и компоненты сервера;
  • Осуществлять администрирование и конфигурирование ролей и компонентов сервера;
  • Писать и использовать сценарии для автоматизации управления и администрирования;
  • Выполнять другие задачи системных администраторов.

Windows PowerShell содержит многие часто используемые утилиты и команды, запускаемые из командной строки, например ipconfig, ping и другие. Сделано это для того, чтобы облегчить переход системных администраторов с командной строки на PowerShell.

Также для удобства многие часто используемые команды и утилиты в PowerShell имеют синонимы (Alias), например cls — это синоним командлета Clear-Host, dir синоним Get-ChildItem (полный список синонимов можно посмотреть путем запуска командлета Get-Alias).

Для упрощения поиска нужной команды в PowerShell есть специальный командлет Get-Command, с помощью которого можно осуществлять поиск, как по глаголу, так и по существительному. Все команды в Windows PowerShell сгруппированы в модули (например, Hyper-V, NetTCPIP), что также упрощает поиск нужной команды.

После того как нужная команда найдена, можно посмотреть инструкцию по работе с этой командой, т.е. справку, для этих целей есть специальный командлет Get-Help, например следующая команда покажет справку по командлету Get-Command:

  
   Get-Help Get-Command

Справка в Windows PowerShell может быть краткой, детальной (параметр -Detailed), полной (параметр -Full), а также можно выводить только примеры (параметр — Examples). Следующая команда покажет только примеры использования командлета Get-Command:

  
   Get-Help Get-Command -Examples

Справка PowerShell обновляемая, т.е. ее можно обновить командой Update-Help.

Заметка! Бесплатная система мониторинга IT инфраструктуры.

Версии Windows PowerShell

Первая версия PowerShell 1.0 появилась 14 ноября 2006 года и выпускалась в виде отдельного дистрибутива, который можно было установить на следующие версии операционных систем Windows: Windows XP Service Pack 2, Windows Server 2003 Service Pack 1 и Windows Vista.

В Windows Server 2008 PowerShell 1.0 поставлялся в виде компонента, который также нужно было устанавливать.

Начиная с Windows 7 и Windows Server 2008 R2, PowerShell поставляется как неотъемлемый компонент системы (т.е. предустановленный, устанавливать его не надо). Ниже представлена таблица соответствия версии PowerShell и версии операционной системы Windows (т.е. какая версия PowerShell по умолчанию установлена в той или иной версии Windows):

Версия PowerShell Версии Windows
PowerShell 2.0 Windows 7, Windows Server 2008 R2
PowerShell 3.0 Windows 8, Windows Server 2012
PowerShell 4.0 Windows 8.1, Windows Server 2012 R2
PowerShell 5.0 Windows 10, Windows Server 2016

С каждой новой версией PowerShell становится все более мощным инструментом администрирования, для сравнения в первой PowerShell было около 130 командлетов, а в PowerShell 5.0 их уже более 600!

Узнать текущую версию PowerShell можно с помощью свойства PSVersion встроенной переменной $PSVersionTable, например, выполните следующую команду:

  
   $PSVersionTable.PSVersion

Или запустите командлет

  
   Get-Variable -Name PSVersionTable –ValueOnly

где, значение PSVersion и будет версией PowerShell.

Язык PowerShell

PowerShell – это объектно-ориентированный скриптовой язык программирования.

Он используется для написания команд управления всеми компонентами операционной системы Windows в оболочке Windows PowerShell, а также для написания сценариев автоматизации задач администрирования в интегрированной среде сценариев Windows PowerShell (ISE). Язык PowerShell хоть и создан для задач администрирования, он является полноценным скриптовым языком программирования, так как имеет программные конструкции, которые присутствуют в каждом языке программирования, такие как: условия, циклы, обработка ошибок, работа с переменными, объектами, массивами.

Язык PowerShell имеет единый синтаксис написания команд и структуру именования этих команд по принципу «Глагол-Существительное», что делает данный язык интуитивно понятным как для программистов, так и для системных администраторов.

Более подробно о программировании на данном языке можете посмотреть в материале — Программирование на языке PowerShell.

Оболочка Windows PowerShell

Оболочка Windows PowerShell – это среда выполнения команд и сценариев на языке PowerShell.

Данная оболочка имеет те же возможности что и командная строка такие как: хранение истории выполнения команд, настройка внешнего вида оболочки, завершение выполнения команд сочетанием клавиш Ctrl+C, а также много других возможностей, которых нет в оболочке командной строки, например такая замечательная возможность как «подсветка синтаксиса» (появилась в PowerShell 5.0).

Запустить оболочку PowerShell можно несколькими способами, например:

  • Из командной строки, набрав PowerShell;
  • Через диалоговое окно «Выполнить» (сочетание клавиш Win+R), также набрав PowerShell;
  • В Windows 7 — Пуск->Все программы ->Стандартные ->Windows PowerShell -> Windows PowerShell;
  • В Windows 8.1 или Windows Server 2012 R2 — Пуск->Все программы ->Служебные ->Windows PowerShell;
  • В Windows 10 или Windows Server 2016 — Пуск->Все программы -> Каталог Windows PowerShell (в группе W) -> Windows PowerShell.

Пример запуска PowerShell в Windows Server 2016

Скриншот 2

Заметка! ТОП 7 популярных языков программирования.

Скриншот оболочки PowerShell в Windows Server 2016

Скриншот 3

Командлеты в PowerShell

Командлет (cmdlet) – это команда Windows PowerShell, с помощью которой можно осуществлять взаимодействие с объектами операционной системы с целью их управления.

Данные команды являются частью языка PowerShell. Командлеты построены по принципу «Глагол-Существительное», разделенные дефисом (-); другими словами, мы сначала указываем, что делать, а через дефис — над чем. Например, командлет Get-Help, где Get — это глагол, означающий «Получить», а Help — существительное «Помощь» в контексте PowerShell «Показать – Справку». Командлеты PowerShell возвращают результаты в виде объектов, что является одним из главных отличий от командной строки Windows, в которой команды возвращают только текст на экран.

Кроме командлетов на получение данных (Get), существуют и такие типы командлетов как:

  • Add – добавление данных;
  • Clear – очистить;
  • Enable – включить;
  • Disable – выключить;
  • New – создать;
  • Remove – удалить;
  • Set – задать;
  • Start — запустить;
  • Stop – остановить;
  • Export – экспортировать;
  • Import – импортировать;
  • И еще много других.

Полный список командлетов в Windows PowerShell можно посмотреть с помощью специального командлета Get-Command. Например, запустите его с параметром -CommandType cmdlet, в итоге на экране у Вас отобразится список командлетов.

  
   Get-Command -CommandType cmdlet

Как Вы уже поняли, у командлетов есть параметры, с помощью которых мы можем конкретизировать действия командлета. Параметры бывают обязательные и необязательные, например, у командлета Get-Command обязательных параметров нет.

Ниже на картинке представлен способ поиска командлета по глаголу (параметр Verb). В данном случае у нас отобразился список командлетов, которые умеют что-то перезапускать.

Скриншот 4

Команда

Курс по SQL для начинающих

  
   Get-Command -Verb Restart

Для поиска командлета по существительному необходимо использовать параметр Noun. Например, ниже мы получили список командлетов, которые работают со службами.

Скриншот 5

Команда

  
   Get-Command -Noun Service

Если Вы не нашли нужный командлет по полному названию можете использовать маску в формате *Текст*.

Конвейер в PowerShell

Одной из главных возможностей Windows PowerShell является возможность использования конвейера при выполнении команд.

Конвейер – это передача результата работы командлета через вертикальную черту (|) другому командлету.

При этом, как Вы помните, в PowerShell командлеты работают с объектами и возвращают объекты, соответственно по конвейеру передаются также объекты.

С помощью конвейера можно выполнять сложные задачи простым и удобным способом без необходимости написания сложных алгоритмов и сценариев.

Например, давайте узнаем название самого большого файла в каталоге «C:WindowsSystem32» (простой пример конвейера).

Скриншот 6

Команда

  
   Get-ChildItem -Path "C:WindowsSystem32" -File | Sort-Object length -Descending | Select-Object -First 1

Где,

  • Get-ChildItem – командлет получения объектов в указанном каталоге;
  • Sort-Object – командлет для сортировки объектов, в нашем случае мы сортируем по размеру файла (length -Descending);
  • Select-Object – командлет выбора нужных свойств объекта, в нашем случае мы выводим стандартные поля и только самый первый объект, т.е. большой файл (параметр -First 1).

Все командлеты отделены друг от друга вертикальной чертой. Результат работы каждого командлета передается на вход другому командлету, т.е. сначала мы получаем все объекты в указанном каталоге, затем сортируем полученный результат и в заключение выбираем самый первый объект.

Фоновое исполнение заданий

В Windows PowerShell есть возможность фонового исполнения заданий, она представляет собой механизм, с помощью которого можно запустить на выполнение команду (например, которая долго выполняется) в фоновом режиме, т.е. после запуска Вы возвращаетесь в текущую сессию и можете продолжить работу, не дожидаясь окончания работы команды. Данная возможность Вам понадобится тогда, когда у Вас возникнет необходимость запустить команду, работа которой занимает достаточно продолжительное время, а как Вы знаете, в течение этого времени сессия оболочки PowerShell блокируется до завершения работы команды, а Вам нужно продолжать работать.

Всеми заданиями, которые запущенны в фоновом режиме, Вы можете управлять, например, посмотреть список заданий, остановить работу задания, удалить задание, и, конечно же, посмотреть результат работы задания.

В Windows PowerShell для работы с фоновыми заданиями есть следующие командлеты:

  • Start-Job – запустить фоновую задачу;
  • Stop-Job – остановить фоновую задачу
  • Get-Job – посмотреть список фоновых задач;
  • Receive-Job – посмотреть результат выполнения фоновой задачи;
  • Remove-Job – удалить фоновую задачу;
  • Wait-Job – перевести фоновую задачу на передний план, для того чтобы дожидаться ее окончания.

Для запуска в фоновом режиме необходимо написать команду Start-Job, а в фигурных скобках {} команду или набор команд, которые необходимо выполнить в фоновом режиме.

Например, давайте запустим какую-нибудь задачу (показать список служб) в фоновом режиме, затем посмотрим на список фоновых заданий и выведем на экран результат работы нашего задания (т.е. список служб).

Запуск задачи в фоновом режиме

  
   Start-Job {Get-Service}

Смотрим на список задач запущенных в фоновом режиме

  
   Get-Job

Отображаем результат работы задания Job1

  
   Receive-Job Job1

Скриншот 7

Как видим, у нас появилась задача со статусом «Completed», т.е. она уже выполнилась (просто Get-Service отрабатывает быстро).

Для того чтобы посмотреть результат работы фоновой задачи, т.е. командлета Get-Service, мы выполнили команду Receive-Job и передали ей имя задания (можно и значение идентификатора). В результате у нас отобразился список служб.

Заметка! Рейтинг популярности антивирусов для домашних компьютеров.

Удаленное управление на PowerShell

Windows PowerShell рассчитан не только на локальное использование, но и на удаленное выполнение команд. Данная возможность необходима, чтобы Вы могли со своего рабочего места управлять удаленными компьютерами, т.е. выполнять команды PowerShell.

Существует несколько способов удаленного управления:

  • С помощью параметра –ComputerName (есть у многих команд). Другими словами Вы передаете имя компьютера, на котором необходимо выполнить команду, в качестве параметра. Способ обладает недостатком, так как ограничивается выполнением одной команды;
  • С помощью сессий. Командлет Enter-PSSession (интерактивный сеанс). Таким способом Вы подключаетесь к удаленному компьютеру и все команды, которые Вы будете набирать в оболочке PowerShell, будут выполняться на удаленном компьютере так же, как если бы Вы набирали команды непосредственно на удаленном компьютере. Способ также обладает недостатком, так как сеанс ограничивается одним компьютером;
  • С помощью командлета Invoke-Command. С помощью данного способа можно выполнять команды или сценарии как на одном компьютере, так и на нескольких.

Например, чтобы подключиться к удаленному компьютеру (в примере ниже ServerName) интерактивным сеансом выполните следующую команду:

  
   Enter-PSSession ServerName

Сценарии, функции и модули в Windows PowerShell

Если Вы написали некий алгоритм, скорей всего Вы захотите сохранить его, для того чтобы в дальнейшем им пользоваться. В Windows PowerShell для этих целей существует механизм использования сценариев.

Суть данного механизма следующая, Вы пишите нужный Вам набор команд и сохраняете его в качестве сценария — это простой текстовый файл с расширением .PS1.

Затем, для того чтобы выполнить этот сценарий, Вы просто запускаете его в оболочке PowerShell. При этом Вам необходимо либо указать полный путь к файлу сценария, либо перейти в каталог со сценарием и вызвать его по имени.

Важно!

По умолчанию выполнение сценариев в Windows запрещено! Для того чтобы посмотреть политику выполнения сценариев выполните командлет Get-ExecutionPolicy. В результате он вернет действующую политику, например:

  • Restricted – блокируется выполнение любых сценариев (значение по умолчанию);
  • AllSigned – разрешено выполнение сценариев, которые имеют цифровую подпись;
  • RemoteSigned – разрешено выполнение локальных сценариев, все скачанные сценарии должны иметь цифровую подпись;
  • Unrestricted — разрешено выполнение любых сценариев (не рекомендуется, так как небезопасно!).

Для разрешения выполнения сценариев необходимо использовать командлет Set-ExecutionPolicy с одним из вышеперечисленных параметров.

Например, для разрешения выполнения локальных сценариев выполним следующую команду, и согласимся с внесением изменений, нажав Y.

  
   Set-ExecutionPolicy RemoteSigned

В сценарии можно передавать параметры, делать их обязательными или задавать значение по умолчанию.

В Windows PowerShell предусмотрен механизм создания собственных функций, которые также как и встроенные командлеты можно будет использовать в оболочке PowerShell.

Для этого необходимо указать ключевое слово Function и затем в фигурных скобках {} написать алгоритм работы этой функции, т.е. набор команд (например, какая-нибудь часто используемая процедура: создать пользователя с определенными правами, очистить определенные каталоги и так далее). Потом необходимо сохранить все это в сценарий, но только уже с расширением .psm1, так как этот файл будет являться уже модулем.

Это еще не все, этот файл необходимо поместить в каталог, в котором PowerShell ищет модули. Таких каталогов несколько (специальный каталог в профиле пользователя, каталог, где установлен PowerShell), их можно посмотреть в переменных окружения PowerShell. Для этого выполните следующую команду

  
   Get-ChildItem Env:PSModulePath | Format-Table -AutoSize

После того как Вы поместите написанный Вами модуль в специальный каталог, Вы сможете обращаться к своим функциям как к обычным командам PowerShell.

Интегрированная среда сценариев Windows PowerShell (ISE)

Для того чтобы было удобно писать сценарии, функции и соответственно модули, компания Microsoft разработала специальную графическую программу Integrated Scripting Environment.

Integrated Scripting Environment (ISE) – интегрированная среда сценариев.

Работать в этой программе очень удобно, к тому же она имеет мощный функционал (создание множества вкладок со сценариями, область вывода, встроенный отладчик и другое).

Запустить ее можно следующим образом:

  • В Windows 7 — Пуск->Все программы ->Стандартные ->Windows PowerShell -> Windows PowerShell ISE;
  • В Windows 10 или Windows Server 2016 — Пуск->Все программы -> Каталог Windows PowerShell (в группе W) -> Windows PowerShell ISE.

Примечание! ISE не будет работать на системе Windows Server, установленной в варианте Server Core.

Скриншот интегрированной среды сценариев PowerShell (ISE) в Windows Server 2016

Скриншот 8

Заметка! ТОП 5 популярных систем управления базами данных (СУБД).

На этом у меня все, надеюсь, материал был Вам полезен! Удачи!

PowerShell

PowerShell Core 6.0 icon.png
PowerShell Core 7.1.5 with Windows Terminal.png

Screenshot of a PowerShell 7 session in Windows Terminal

Paradigm Imperative, pipeline, object-oriented, functional and reflective
Designed by Jeffrey Snover, Bruce Payette, James Truher (et al.)
Developer Microsoft
First appeared November 14, 2006; 16 years ago
Stable release

7.3.2
/ January 24, 2023; 50 days ago[1]

Preview release

v7.3.0-preview.7
/ August 11, 2022; 7 months ago[2]

Typing discipline Strong, safe, implicit and dynamic
Implementation language C#
Platform PowerShell: .NET
Windows PowerShell: .NET Framework
OS
  • Windows 7 and later
  • Windows Server 2008 R2 and later
  • macOS 10.12 and later
  • Ubuntu 14.04, 16.04, 18.04, 20.04 and 22.04
  • Debian 8.7+, 9, 10 and 11
  • CentOS 7 and 8
  • Red Hat Enterprise Linux 7 and 8
  • openSUSE 42.2, 42.3, 15.0, 15.1, 15.2
  • Fedora 28, 29, 30
License MIT License[3] (but the Windows component remains proprietary)
Filename extensions
  • .ps1 (Script)
  • .ps1xml (XML Document)
  • .psc1 (Console File)
  • .psd1 (Data File)
  • .psm1 (Script Module)
  • .pssc (Session Configuration File)
  • .psrc (Role Capability File)
  • .cdxml (Cmdlet Definition XML Document)
Website microsoft.com/powershell
Influenced by
Python, Ksh, Perl, C#, CL, DCL, SQL, Tcl, Tk,[4] Chef, Puppet

PowerShell is a task automation and configuration management program 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.[5] The former is built on the .NET Framework, the latter on .NET (previously .NET Core).

In PowerShell, administrative tasks are generally performed via cmdlets (pronounced command-lets), which are specialized .NET classes implementing a particular operation. These work by accessing data in different data stores, like the file system or Windows Registry, which are made available to PowerShell via providers. Third-party developers can add cmdlets and providers to PowerShell.[6][7] Cmdlets may be used by scripts, which may in turn be packaged into modules. Cmdlets work in tandem with the .NET API.

PowerShell’s support for .NET Remoting, WS-Management, CIM, and SSH enables administrators to perform administrative tasks on both local and remote Windows systems. 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.[6][8] Other Microsoft applications including Microsoft SQL Server 2008 also expose their management interface via PowerShell cmdlets.[9]

PowerShell includes its own extensive, console-based help (similar to man pages in Unix shells) 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[edit]

The command-line interpreter (CLI) has been an inseparable part of most Microsoft operating systems. MS-DOS and Xenix relied almost exclusively on CLI. (MS-DOS 5 came with a complementary graphical DOS Shell.) The Windows 9x family came bundled with COMMAND.COM, the command-line environment of MS-DOS. The Windows NT and Windows CE families, however, came with a new cmd.exe that bore strong similarities to COMMAND.COM. Both environments support a few basic internal commands and a primitive scripting language (batch files), which can be used to automate various tasks. However, they cannot automate all facets of Windows graphical user interface (GUI) because command-line equivalents of operations are limited and the scripting language is elementary.

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 (COM). 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 (such as netsh and WMIC) with their own command sets but they were not interoperable. Windows Server 2003 further attempted to improve the command line experience but scripting support was still unsatisfactory.[10]

Kermit[edit]

By the late 1990s, Intel had come to Microsoft asking for help in making Windows, which ran on Intel CPUs, a more appropriate platform to support the development of future Intel CPUs. At the time, Intel CPU development was accomplished on Sun Microsystems computers which ran Solaris (a Unix variant) on RISC-architecture CPUs. The ability to run Intel’s many KornShell automation scripts on Windows was identified as a key capability. Internally, Microsoft began an effort to create a Windows port of Korn Shell, which was code-named Kermit.[11] Intel ultimately pivoted to a Linux-based development platform that could run on Intel CPUs, rendering the Kermit project redundant. However, with a fully funded team, Microsoft program manager Jeffrey Snover realized there was an opportunity to create a more general-purpose solution to Microsoft’s problem of administrative automation.

Monad[edit]

By 2002, Microsoft had started to develop a new approach to command-line management, including a CLI called Monad (also known as Microsoft Shell or MSH). The ideas behind it were published in August 2002 in a white paper called the «Monad Manifesto» by its chief architect, Jeffrey Snover.[12] In a 2017 interview, Snover explains the genesis of PowerShell, saying that he had been trying to make Unix tools available on Windows, which didn’t work due to «core architectural difference[s] between Windows and Linux». Specifically, he noted that Linux considers everything an ASCII text file, whereas Windows considers everything an «API that returns structured data». They were fundamentally incompatible, which led him to take a different approach.[13]

Monad was to be a new extensible CLI with a fresh design capable of automating a range of core administrative tasks. Microsoft first demonstrated Monad publicly at the Professional Development Conference in Los Angeles in October 2003. A few months later, they opened up private beta, which eventually led to a public beta. Microsoft published the first Monad public beta release on 17 June 2005 and the Beta 2 on 11 September 2005, and Beta 3 on 10 January 2006.

PowerShell[edit]

On 25 April 2006, not long after the initial Monad announcement, Microsoft announced that Monad had been renamed Windows PowerShell, positioning it as a significant part of its management technology offerings.[14] Release Candidate (RC) 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, rather than a mere add-on.

Release Candidate 2 of PowerShell version 1 was released on 26 September 2006, with final release to the web on 14 November 2006. PowerShell for earlier versions of Windows was released on 30 January 2007.[15] PowerShell v2.0 development began before PowerShell v1.0 shipped. During the development, Microsoft shipped three community technology previews (CTP). Microsoft made these releases available to the public. The last CTP release of Windows PowerShell v2.0 was made available in December 2008.

PowerShell for Linux 7.3.1 on Ubuntu 22.10

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.[16] In an October 2009 issue of TechNet Magazine, Microsoft called proficiency with PowerShell «the single most important skill a Windows administrator will need in the coming years».[17]

Windows 10 shipped a testing framework for PowerShell.[18]

On 18 August 2016, Microsoft announced[19] that they had made PowerShell open-source and cross-platform with support for Windows, macOS, CentOS and Ubuntu.[5] The source code was published on GitHub.[20] 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.[21] Starting with version 5.1, PowerShell Core is bundled with Windows Server 2016 Nano Server.[22][23]

Design[edit]

A key design tactic for PowerShell was to leverage the large number of APIs that already existed in Windows, Windows Management Instrumentation, .NET Framework, and other software. PowerShell cmdlets «wrap around» existing functionality. The intent with this tactic is to provide an administrator-friendly, more-consistent interface between administrators and a wide range of underlying functionality. With PowerShell, an administrator doesn’t need to know .NET, WMI, or low-level API coding, and can instead focus on using the cmdlets exposed by PowerShell. In this regard, PowerShell creates little new functionality, instead focusing on making existing functionality more accessible to a particular audience.[24]

Grammar[edit]

PowerShell’s developers based the core grammar of the tool on that of the POSIX 1003.2 KornShell.[25]

However, PowerShell’s language was also influenced by PHP, Perl, and many other existing languages.[26]

Named Commands[edit]

Windows PowerShell can execute four kinds of named commands:[27]

  • cmdlets (.NET Framework 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 launches it in a separate process; if it is a cmdlet, it executes in the PowerShell process. PowerShell provides an interactive command-line interface, where 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.[28]

Extended Type System[edit]

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.[29]

Cmdlets[edit]

Cmdlets are specialized commands in the PowerShell environment that implement specific functions. These are the native commands in the PowerShell stack. Cmdlets follow a VerbNoun naming pattern, such as Get-ChildItem, which makes it self-documenting code.[30] 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.[30]

Cmdlets are specialized .NET classes, which the PowerShell runtime instantiates and invokes at execution time. Cmdlets derive either from Cmdlet or from PSCmdlet, the latter being used when the cmdlet needs to interact with the PowerShell runtime.[30] 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.[31] 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.[32][33]

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[34] 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.[35]

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.[36] 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 a database), they can add specific providers as well.[citation needed]

The number of cmdlets included in the base PowerShell install has generally increased with each version:

Version Cmdlets
Windows PowerShell 1.0 129[37]
Windows PowerShell 2.0 632[38]
Windows PowerShell 3.0 about 1,000[39]
Windows PowerShell 4.0 ?
Windows PowerShell 5.0 about 1,300[40]
Windows PowerShell 5.1 1586[citation needed]
PowerShell Core 6.0 ?
PowerShell Core 6.1 ?
PowerShell Core 6.2 ?
PowerShell 7.0 1507[citation needed]
PowerShell 7.1 ?
PowerShell 7.2 ?

Cmdlets can be added into the shell through snap-ins (deprecated in v2) and modules; users are not limited to the cmdlets included in the base PowerShell installation.

Pipeline[edit]

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 (e.g., to sort the objects by handle count), and then finally to the Select-Object cmdlet to select just the first ten processes based on handle count.[citation needed]

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. Additionally, 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.[41] An object can also encapsulate certain functions that work on the contained data, which become available to the recipient command for use.[42][43] 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.[44][45]

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 backward 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.[46][47][48]

Scripting[edit]

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,[49] 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 (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.[50] 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.[51][52]

Using the function keyword, PowerShell provides for the creation of functions. A simple function has the following general look:[53]

function name ([Type]$Param1, [Type]$Param2)
{
  # Instructions
}

However, PowerShell allows for advanced functions that support named parameters, positional parameters, switch parameters and dynamic parameters.[53]

function Verb-Noun
{
  param (
    # Definition of static parameters
  )
  dynamicparam {
    # Definition of dynamic parameters
  }
  begin {
    # Set of instruction to run at the start of the pipeline
  }
  process {
    # Main instruction sets, ran for each item in the pipeline
  }
  end {
    # Set of instruction to run at the end of the pipeline
  }
}

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

name value1 value2
Verb-Noun -Param1 value1 -Param2 value2

PowerShell allows any static .NET methods to be called by providing their namespaces enclosed in brackets ([]), and then using a pair of colons (::) to indicate the static method.[54] For example:

[Console]::WriteLine("PowerShell")

There are dozens of ways to create objects in PowerShell. Once created, one can access the properties and instance methods of an object using the . notation.[54]

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.[55]

The following list of special characters is supported by PowerShell:[56]

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). 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.[57]

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 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.[58] 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.[59]

The PowerShell scripting language supports binary prefix notation similar to the scientific notation supported by many programming languages in the C-family.[60]

Hosting[edit]

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 (one instantiation of the PowerShell runtime), which runs in the application’s process and is exposed as a Runspace object.[6] 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.[citation needed]

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.[6] 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.[6] 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.[citation needed]

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 (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.[citation needed]

Desired State Configuration[edit]

DSC allows for declaratively specifying how a software environment should be configured.[61]

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 (LCM) periodically polls the system using the control flow described by resources (imperative pieces of DSC) to make sure that the state of a configuration is maintained.

Versions[edit]

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

Windows PowerShell 1.0[edit]

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

Windows PowerShell 2.0[edit]

PowerShell 2.0 is integrated with Windows 7 and Windows Server 2008 R2[63] and is released for Windows XP with Service Pack 3, Windows Server 2003 with Service Pack 2, and Windows Vista with Service Pack 1.[64][65]

PowerShell v2 includes changes to the scripting language and hosting API, in addition to including more than 240 new cmdlets.[66][67]

New features of PowerShell 2.0 include:[68][69][70]

  • PowerShell remoting: Using WS-Management, PowerShell 2.0 allows scripts and cmdlets to be invoked on a remote machine or a large set of remote machines.
  • Background jobs: Also called a PSJob, it allows a command sequence (script) or pipeline to be invoked asynchronously. Jobs can be run on the local machine or on multiple remote machines. An interactive cmdlet in a PSJob blocks the execution of the job until user input is provided.
  • Transactions: Enable cmdlet and developers can perform transactional operations. PowerShell 2.0 includes transaction cmdlets for starting, committing, and rolling back a PSTransaction as well as features to manage and direct the transaction to the participating cmdlet and provider operations. The PowerShell Registry provider supports transactions.
  • Advanced functions: These are cmdlets written using the PowerShell scripting language. Initially called «script cmdlets», this feature was later renamed «advanced functions».[71]
  • SteppablePipelines: This allows the user to control when the BeginProcessing(), ProcessRecord() and EndProcessing() functions of a cmdlet are called.
  • Modules: This allows script developers and administrators to organize and partition PowerShell scripts in self-contained, reusable units. Code from a module executes in its own self-contained context and does not affect the state outside the module. Modules can define a restricted runspace environment by using a script. They have a persistent state as well as public and private members.
  • Data language: A domain-specific subset of the PowerShell scripting language that allows data definitions to be decoupled from the scripts and allows localized string resources to be imported into the script at runtime (Script Internationalization).
  • Script debugging: It allows breakpoints to be set in a PowerShell script or function. Breakpoints can be set on lines, line & columns, commands and read or write access of variables. It includes a set of cmdlets to control the breakpoints via script.
  • Eventing: This feature allows listening, forwarding, and acting on management and system events. Eventing allows PowerShell hosts to be notified about state changes to their managed entities. It also enables PowerShell scripts to subscribe to ObjectEvents, PSEvents, and WmiEvents and process them synchronously and asynchronously.
  • Windows PowerShell Integrated Scripting Environment (ISE): PowerShell 2.0 includes a GUI-based PowerShell host that provides integrated debugger, syntax highlighting, tab completion and up to 8 PowerShell Unicode-enabled consoles (Runspaces) in a tabbed UI, as well as the ability to run only the selected parts in a script.
  • Network file transfer: Native support for prioritized, throttled, and asynchronous transfer of files between machines using the Background Intelligent Transfer Service (BITS).[72]
  • New cmdlets: Including Out-GridView, which displays tabular data in the WPF GridView object, on systems that allow it, and if ISE is installed and enabled.
  • New operators: -Split, -Join, and Splatting (@) operators.
  • Exception handling with Try-Catch-Finally: Unlike other .NET languages, this allows multiple exception types for a single catch block.
  • Nestable Here-Strings: PowerShell Here-Strings have been improved and can now nest.[73]
  • Block comments: PowerShell 2.0 supports block comments using <# and #> as delimiters.[74]
  • New APIs: The new APIs range from handing more control over the PowerShell parser and runtime to the host, to creating and managing collection of Runspaces (RunspacePools) as well as the ability to create Restricted Runspaces which only allow a configured subset of PowerShell to be invoked. The new APIs also support participation in a transaction managed by PowerShell

Windows PowerShell 3.0[edit]

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.[75][76]

PowerShell 3.0 is part of a larger package, Windows Management Framework 3.0 (WMF3), which also contains the WinRM service to support remoting.[76] Microsoft made several Community Technology Preview releases of WMF3. An early community technology preview 2 (CTP 2) version of Windows Management Framework 3.0 was released on 2 December 2011.[77] Windows Management Framework 3.0 was released for general availability in December 2012[78] and is included with Windows 8 and Windows Server 2012 by default.[79]

New features in PowerShell 3.0 include:[76][80]: 33–34 

  • Scheduled jobs: Jobs can be scheduled to run on a preset time and date using the Windows Task Scheduler infrastructure.
  • Session connectivity: Sessions can be disconnected and reconnected. Remote sessions have become more tolerant of temporary network failures.
  • Improved code writing: Code completion (IntelliSense) and snippets are added. PowerShell ISE allows users to use dialog boxes to fill in parameters for PowerShell cmdlets.
  • Delegation support: Administrative tasks can be delegated to users who do not have permissions for that type of task, without granting them perpetual additional permissions.
  • Help update: Help documentations can be updated via Update-Help command.
  • Automatic module detection: Modules are loaded implicitly whenever a command from that module is invoked. Code completion works for unloaded modules as well.
  • New commands: Dozens of new modules were added, including functionality to manage disks get-WmiObject win32_logicaldisk, volumes, firewalls, network connections, and printers, which had previously been performed via WMI.[further explanation needed]

Windows PowerShell 4.0[edit]

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.[81]

New features in PowerShell 4.0 include:

  • Desired State Configuration:[82][83][84] Declarative language extensions and tools that enable the deployment and management of configuration data for systems using the DMTF management standards and WS-Management Protocol
  • New default execution policy: On Windows Servers, the default execution policy is now RemoteSigned.
  • Save-Help: Help can now be saved for modules that are installed on remote computers.
  • Enhanced debugging: The debugger now supports debugging workflows, remote script execution and preserving debugging sessions across PowerShell session reconnections.
  • -PipelineVariable switch: A new ubiquitous parameter to expose the current pipeline object as a variable for programming purposes
  • Network diagnostics to manage physical and Hyper-V’s virtualized network switches
  • Where and ForEach method syntax provides an alternate method of filtering and iterating over objects.

Windows PowerShell 5.0[edit]

Windows Management Framework (WMF) 5.0 RTM which includes PowerShell 5.0 was re-released to web on 24 February 2016, following an initial release with a severe bug.[85]

Key features included:

  • The new class keyword that creates classes for object-oriented programming
  • The new enum keyword that creates enums
  • OneGet cmdlets to support the Chocolatey package manager[86]
  • Extending support for switch management to layer 2 network switches.[87]
  • Debugging for PowerShell background jobs and instances of PowerShell hosted in other processes (each of which is called a «runspace»)
  • Desired State Configuration (DSC) Local Configuration Manager (LCM) version 2.0
  • DSC partial configurations
  • DSC Local Configuration Manager meta-configurations
  • Authoring of DSC resources using PowerShell classes

Windows PowerShell 5.1[edit]

It was released along with the Windows 10 Anniversary Update[88] on August 2, 2016, and in Windows Server 2016.[89] 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.[90] 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,[91] and was released on January 19, 2017.[92]

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 the .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.[23] This was the final version of PowerShell made exclusively for Windows.

PowerShell Core 6[edit]

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.[5] It achieved general availability on 10 January 2018 for Windows, macOS and Linux.[93] 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.[94]

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.[95]

6.1[edit]

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.»[96] Still, no details of these cmdlets can be found in the full version of the change log.[97] Microsoft later professes that this number was insufficient as PowerShell Core failed to replace Windows PowerShell 5.1 and gain traction on Windows.[98] It was, however, popular on Linux.[98]

6.2[edit]

PowerShell Core 6.2 is focused primarily on performance improvements, bug fixes, and smaller cmdlet and language enhancements that improved developer productivity.[99]

PowerShell 7[edit]

PowerShell 7 is the replacement for PowerShell Core 6.x products as well as Windows PowerShell 5.1, which is the last supported Windows PowerShell version.[100][98] The focus in development was to make PowerShell 7 a viable replacement for Windows PowerShell 5.1, i.e. to have near parity with Windows PowerShell in terms of compatibility with modules that ship with Windows.[101]

New features in PowerShell 7 include:[102]

  • The -Parallel switch for the ForEach-Object cmdlet to help handle parallel processing
  • Near parity with Windows PowerShell in terms of compatibility with built-in Windows modules
  • A new error view
  • The Get-Error cmdlet
  • Pipeline chaining operators (&& and ||) that allow conditional execution of the next cmdlet in the pipeline
  • The ?: operator for ternary operation
  • The ?? operator for null coalescing
  • The ??= operator for null coalescing assignment
  • Cross-platform Invoke-DscResource (experimental)
  • Return of the Out-GridView cmdlet
  • Return of the -ShowWindow switch for the Get-Help

PowerShell 7.2[edit]

PowerShell 7.2 is the next long-term support version of PowerShell, after version 7.0. It uses .NET 6.0 and features universal installer packages for Linux. On Windows, updates to PowerShell 7.2 and later come via the Microsoft Update service; this feature has been missing from PowerShell 6.0 through 7.1.[103]

PowerShell 7.3[edit]

This version includes some general Cmdlet updates and fixes, testing for framework dependent package in release pipeline as well as build and packaging improvements.[104]

PowerShell 7.4.0[edit]

A new PowerShell preview release is available: v7.4.0-preview.2

  Upgrade now, or check out the release page at:
    https://aka.ms/PowerShell-Release?tag=v7.4.0-preview.2

Comparison of cmdlets with similar commands[edit]

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.

Notes

  1. ^ ls alias is absent in the Linux version of PowerShell Core.
  2. ^ While the external ping command remains available to PowerShell, Test-Connection’s output is a structured object that can be programmatically inspected.[105]
  3. ^ Clear-Host is implemented as a predefined PowerShell function.
  4. ^ a b Available in Windows NT 4, Windows 98 Resource Kit, Windows 2000 Support Tools
  5. ^ a b Introduced in Windows XP Professional Edition
  6. ^ Also used in UNIX to send a process any signal, the «Terminate» signal is merely the default
  7. ^ curl and wget aliases are absent from PowerShell Core, so as to not interfere with invoking similarly named native commands.

Filename extensions[edit]

Extension Description
.ps1 Script file[107]
.psd1 Module’s manifest file; usually comes with a script module or binary module[108]
.psm1 Script module file[109]
.dll DLL-compliant[a] binary module file[110]
.ps1xml Format and type definitions file[48][111]
.xml XML-compliant[b] serialized data file[112]
.psc1 Console file[113]
.pssc Session configuration file[114]
.psrc Role Capability file[115]
  1. ^ Dynamic-link library (DLL) is not a PowerShell-only format. It is a generic format for storing compiled .NET assembly’s code.
  2. ^ XML is not a PowerShell-only format. It is a popular information interchange format.

Application support[edit]

Application Version Cmdlets Provider Management GUI
Exchange Server 2007 402 Yes Yes
Windows Server 2008 Yes Yes No
Microsoft SQL Server 2008 Yes Yes No
Microsoft SharePoint 2010 Yes Yes No
System Center Configuration Manager 2012 R2 400+ Yes No
System Center Operations Manager 2007 74 Yes No
System Center Virtual Machine Manager 2007 Yes Yes Yes
System Center Data Protection Manager 2007 Yes No No
Windows Compute Cluster Server 2007 Yes Yes No
Microsoft Transporter Suite for Lotus Domino[116] 08.02.0012 47 No No
Microsoft PowerTools for Open XML[117] 1.0 33 No No
IBM WebSphere MQ[118] 6.0.2.2 44 No No
IoT Core Add-ons[119] 74 Un­known Un­known
Quest Management Shell for Active Directory[120] 1.7 95 No No
Special Operations Software Specops Command[121] 1.0 Yes No Yes
VMware vSphere PowerCLI[122] 6.5 R1 500+ Yes Yes
Internet Information Services[123] 7.0 54 Yes No
Windows 7 Troubleshooting Center[124] 6.1 Yes No Yes
Microsoft Deployment Toolkit[125] 2010 Yes Yes Yes
NetApp PowerShell Toolkit[126][127] 4.2 2000+ Yes Yes
JAMS Scheduler – Job Access & Management System[128] 5.0 52 Yes Yes
UIAutomation[129] 0.8 432 No No
Dell Equallogic[130] 3.5 55 No No
LOGINventory[131] 5.8 Yes Yes Yes
SePSX[132] 0.4.1 39 No No

Alternative implementation[edit]

A project named Pash, a pun on the widely known «bash» Unix shell, has been an open-source and cross-platform reimplementation of PowerShell via the Mono framework.[133] 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,[134] and finally ceased in 2016 when PowerShell was officially made open-source and cross-platform.[135]

See also[edit]

  • Common Information Model (computing)
  • Comparison of command shells
  • Comparison of programming languages
  • Web-Based Enterprise Management
  • Windows Script Host
  • Windows Terminal

References[edit]

  1. ^ «v7.3.2 Release of PowerShell». PowerShell/PowerShell repo. Microsoft. Retrieved 2023-01-24 – via GitHub.com.
  2. ^ «v7.3.0-preview.7 Release of PowerShell». PowerShell/PowerShell repo. Microsoft. Retrieved 2022-08-12 – via GitHub.com.
  3. ^ «PowerShell for every system!». 12 June 2017 – via GitHub.com.
  4. ^ Snover, Jeffrey (May 25, 2008). «PowerShell and WPF: WTF». Windows PowerShell Blog. Microsoft.
  5. ^ a b c Bright, Peter (2016-08-18). «PowerShell is Microsoft’s latest open source release, coming to Linux, OS X». Ars Technica. Condé Nast. Archived from the original on 2020-04-09. Retrieved 2020-05-12.
  6. ^ a b c d e «powershell». Retrieved 2023-03-13.
  7. ^ Truher, Jim (December 2007). «Extend Windows PowerShell With Custom Commands». MSDN Magazine. Microsoft. Archived from the original on 6 October 2008.
  8. ^ Lowe, Scott (January 4, 2007). «Exchange 2007: Get used to the command line». TechRepublic. CBS Interactive. Archived from the original on 2018-11-16. Retrieved 2020-05-12.
  9. ^ Snover, Jeffrey (2007-11-13). «SQL Server Support for PowerShell!». Windows PowerShell Blog (blog posting). Microsoft. Archived from the original on 2007-11-15. Retrieved 2007-11-13.
  10. ^ Dragan, Richard V. (April 23, 2003). «Windows Server 2003 Delivers Improvements All Around». PCMag.com. Ziff Davis. A standout feature here is that virtually all admin utilities now work from the command line (and most are available through telnet).
  11. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. p. 25. ISBN 978-1-9536450-3-6.
  12. ^ Jeffrey P. Snover (8 August 2002). «Monad Manifesto» (PDF). Windows PowerShell Blog. Microsoft. Retrieved 2 April 2021.
  13. ^ Biggar and Harbaugh (2017-09-14). «The Man Behind Windows PowerShell». To Be Continuous (Podcast). Heavybit. Retrieved 2017-09-14.
  14. ^ «Windows PowerShell (Monad) Has Arrived». Windows PowerShell Blog. Microsoft. April 25, 2006.
  15. ^ Snover, Jeffrey (November 15, 2006). «Windows PowerShell & Windows Vista». Windows PowerShell Blog (blog posting). Microsoft.
  16. ^ «Windows Management Framework (Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0)». Support. Microsoft. September 30, 2013. Archived from the original on October 13, 2013.
  17. ^ Posey, Brien (6 October 2009). «10 reasons why you should learn to use PowerShell». TechRepublic. Retrieved 2 April 2021.
  18. ^ «What is Pester and Why Should I Care?». 14 December 2015.
  19. ^ Snover, Jeffrey (18 August 2016). «PowerShell is open sourced and is available on Linux». Microsoft Azure Blog. Microsoft.
  20. ^ «PowerShell/PowerShell». GitHub. Retrieved 2016-08-18.
  21. ^ Hansen, Kenneth; Calvo, Angel (August 18, 2016). «PowerShell on Linux and Open Source!». Windows PowerShell Blog. Microsoft.
  22. ^ Foley, Mary Jo (August 18, 2016). «Microsoft open sources PowerShell; brings it to Linux and Mac OS X». ZDNet. CBS Interactive.
  23. ^ a b «PowerShell on Nano Server». TechNet. Microsoft. 20 October 2016.
  24. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. p. 45. ISBN 978-1-9536450-3-6.
  25. ^
    Payette, Bruce (2007). Windows PowerShell in Action. Manning Pubs Co Series. Manning. p. 27. ISBN 9781932394900. Retrieved 2016-07-22. The core PowerShell language is based on the POSIX 1003.2 grammar for the Korn shell.
  26. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. p. 109. ISBN 978-1-9536450-3-6.
  27. ^ «about_Command_Precedence». TechNet. Microsoft. May 8, 2014.
  28. ^ Wheeler, Sean (2021-09-07). «about Parsing — PowerShell». Microsoft Docs. Retrieved 2021-12-05.{{cite web}}: CS1 maint: url-status (link)
  29. ^ «Windows PowerShell Extended Type System». Retrieved 2007-11-28.
  30. ^ a b c «Windows PowerShell Cmdlets». Retrieved 2007-11-28.
  31. ^ «Creating Your First Cmdlet». Retrieved 2007-11-28.
  32. ^ «Get-Verb». TechNet. Microsoft. May 8, 2014.
  33. ^ «Cmdlet Overview». MSDN. Microsoft. May 8, 2014.
  34. ^ «Adding parameters That Process Command Line Input». Retrieved 2007-11-28.
  35. ^ «Adding parameters That Process Pipeline Input». Retrieved 2007-11-28.
  36. ^ «Windows PowerShell Providers». Retrieved 2010-10-14.
  37. ^ Yoshizawa, Tomoaki; Ramos, Durval (29 September 2012). «PowerShell 1.0 Cmdlets». TechNet Articles. Microsoft.
  38. ^ Yoshizawa, Tomoaki (10 July 2012). «PowerShell 2.0 Cmdlets». TechNet Articles. Microsoft.
  39. ^ Wilson, Ed (2013). «1: Overview of Windows PowerShell 3.0». Windows Powershell 3.0 Step by Step. Sebastopol, California: Microsoft Press. ISBN 978-0-7356-7000-6. OCLC 829236530. Windows PowerShell 3.0 comes with about 1,000 cmdlets on Windows 8
  40. ^ Wilson, Ed (2015). «1: Overview of Windows PowerShell 5.0». Windows PowerShell Step by Step (Third ed.). Redmond, Washington: Microsoft Press. ISBN 978-1-5093-0043-3. OCLC 927112976. Windows PowerShell 5.0 comes with about 1,300 cmdlets on Windows 10
  41. ^ «Windows PowerShell Owner’s Manual: Piping and the Pipeline in Windows PowerShell». TechNet. Microsoft. Retrieved 2011-09-27.
  42. ^ Jones, Don (2008). «Windows PowerShell – Rethinking the Pipeline». Microsoft TechNet. Microsoft. Retrieved 2007-11-28.
  43. ^ «Windows PowerShell Object Concepts». Archived from the original on August 19, 2007. Retrieved 2007-11-28.
  44. ^ «How PowerShell Formatting and Outputting REALLY works». Retrieved 2007-11-28.
  45. ^ «More – How does PowerShell formatting really work?». Retrieved 2007-11-28.
  46. ^ «about_Pipelines». TechNet. Microsoft. May 8, 2014.
  47. ^ «about_Objects». TechNet. Microsoft. May 8, 2014.
  48. ^ a b «about_Format.ps1xml». TechNet. Microsoft. May 8, 2014.
  49. ^ «Anonymous Functions and Code Blocks in PowerShell». Retrieved 2012-01-21.
  50. ^ «Introduction to Windows PowerShell’s Variables». Retrieved 2007-11-28.
  51. ^ «Byte Conversion». Windows PowerShell Tip of the Week. Retrieved 15 November 2013.
  52. ^ Ravikanth (20 May 2013). «Converting to size units (KB, MB, GB, TB, and PB) without using PowerShell multipliers». PowerShell Magazine.
  53. ^ a b c «about_Functions». Microsoft TechNet. Microsoft. 17 October 2013. Retrieved 15 November 2013.
  54. ^ a b «Lightweight Testing with Windows PowerShell». Retrieved 2007-11-28.
  55. ^ Angelopoulos, Alex; Karen, Bemowski (4 December 2007). «PowerShell Got Smart About Smart Quotes». Windows IT Pro. Penton Media. Retrieved 15 November 2013.
  56. ^ «About Special Characters». Powershell / Scripting. Microsoft. June 8, 2017. Retrieved June 20, 2019.
  57. ^ «Trap [Exception] { «In PowerShell» }». Retrieved 2007-11-28.
  58. ^ «Running Windows PowerShell Scripts». Microsoft. Retrieved 2007-11-28.
  59. ^ «about_Signing». Microsoft TechNet. Microsoft. 17 October 2013. Retrieved 15 November 2013.
  60. ^ Lee Holmes (September 2006). Windows PowerShell Quick Reference. O’Reilly Media.
  61. ^ eslesar. «Windows PowerShell Desired State Configuration Overview». msdn.microsoft.com.
  62. ^ Chung, Leonard; Snover, Jeffrey; Kumaravel, Arul (14 November 2006). «It’s a Wrap! Windows PowerShell 1.0 Released!». Windows PowerShell Blog. Microsoft.
  63. ^ «PowerShell will be installed by default on Windows Server 08 R2 (WS08R2) and Windows 7 (W7)!». Windows PowerShell Blog. Microsoft. 2008-10-28. Retrieved 2011-09-27.
  64. ^ «Windows Management Framework is here!». 2009-10-27. Retrieved 2009-10-30.
  65. ^ «Microsoft Support Knowledge Base: Windows Management Framework (Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0)». Support.microsoft.com. 2011-09-23. Retrieved 2011-09-27.
  66. ^ «574 Reasons Why We Are So Proud and Optimistic About W7 and WS08R2». Windows PowerShell Blog. Microsoft. 2008-10-29. Retrieved 2011-09-27.
  67. ^ Snover, Jeffrey (2008). «PowerShell: Creating Manageable Web Services». Archived from the original on October 13, 2008. Retrieved July 19, 2015.
  68. ^ «What’s New in CTP of PowerShell 2.0». Retrieved 2007-11-28.
  69. ^ «Windows PowerShell V2 Community Technology Preview 2 (CTP2) – releaseNotes». Microsoft. Archived from the original on May 6, 2008. Retrieved 2008-05-05.
  70. ^ «Differences between PowerShell 1.0 and PowerShell 2.0». Archived from the original on 2010-09-17. Retrieved 2010-06-26.
  71. ^ Jones, Don (May 2010). «Windows PowerShell: Writing Cmdlets in Script». TechNet Magazine. Microsoft.
  72. ^ «GoGrid Snap-in – Managing Cloud Services with PowerShell». Windows PowerShell Blog. Microsoft. 2008-10-14. Retrieved 2011-09-27.
  73. ^ «Emit-XML». Windows PowerShell Blog. Microsoft. 2008-10-17. Retrieved 2011-09-27.
  74. ^ «Block Comments in V2». Windows PowerShell Blog. Microsoft. 2008-06-14. Retrieved 2011-09-27.
  75. ^ Lee, Thomas (13 August 2012). «PowerShell Version 3 is RTM!». Under The Stairs. Retrieved 2012-08-13.
  76. ^ a b c «Windows Management Framework 3.0». Download Center. Microsoft. 4 September 2012. Retrieved 2012-11-08.
  77. ^ «Windows Management Framework 3.0 Community Technology Preview (CTP) #2 Available for Download». Windows PowerShell Blog. Microsoft. 2 December 2011.
  78. ^ «Windows Management Framework 3.0». Download Center. Microsoft. 3 December 2012.
  79. ^ Jofre, JuanPablo (December 14, 2016). «Windows PowerShell System Requirements». Microsoft Developer Network. Microsoft. Retrieved April 20, 2017.
  80. ^ Honeycutt, Jerry (2012). Woolley, Valerie (ed.). Introducing Windows 8: An Overview for IT Professionals. Redmond, WA: Microsoft Press. ISBN 978-0-7356-7050-1.
  81. ^ «Windows Management Framework 4.0 is now available». Microsoft. 24 October 2013. Retrieved 4 November 2013.
  82. ^ Levy, Shay (25 June 2013). «New Features in Windows PowerShell 4.0». PowerShell Magazine. Retrieved 26 June 2013.
  83. ^ «Desired State Configuration in Windows Server 2012 R2 PowerShell». Channel 9. Microsoft. 3 June 2013. Archived from the original on 26 December 2013. Retrieved 26 June 2013.
  84. ^ Hall, Adrian (7 June 2013). «Thoughts from Microsoft TechEd North America». Blogs: Tips & Tricks. Splunk. Retrieved 26 June 2013.
  85. ^ «Windows Management Framework (WMF) 5.0 RTM packages has been republished». Windows PowerShell Blog. Microsoft. February 24, 2016.
  86. ^ «Q and A». GitHub. Retrieved 21 April 2015.
  87. ^ Snover, Jeffrey (2014-04-03). «Windows Management Framework V5 Preview». blogs.technet.com. Microsoft. Archived from the original on 2014-06-30. Retrieved 2015-04-21.
  88. ^ says, Jaap Brasser (2 August 2016). «#PSTip New PowerShell Commands in Windows 10 Anniversary Update».
  89. ^ «What’s New In Windows Server 2016 Standard Edition Part 9 – Management And Automation».
  90. ^ «Microsoft.PowerShell.LocalAccounts Module». technet.microsoft.com.
  91. ^ «Announcing Windows Management Framework (WMF) 5.1 Preview». 16 July 2016.
  92. ^ «WMF 5.1». Microsoft Download Center.
  93. ^ Aiello, Joey (11 January 2018). «PowerShell Core 6.0: Generally Available (GA) and Supported!». PowerShell Team Blog. Microsoft. Archived from the original on 11 June 2018. Retrieved 11 June 2018.
  94. ^ Aiello, Joey; Wheeler, Sean (10 January 2018). «PowerShell Core Support Lifecycle». Microsoft Docs. Microsoft.
  95. ^ Calvo, Angel (11 January 2018). «Top 10 most exciting reasons to migrate». PowerShell AMA. Microsoft.
  96. ^ Aiello, Joey (2018-09-13). «Announcing PowerShell Core 6.1». devblogs.microsoft.com. Microsoft. Retrieved 2019-06-01.
  97. ^ «PowerShell/PowerShell». GitHub. Retrieved 2020-06-22.
  98. ^ a b c Lee, Steve (2019-04-05). «The Next Release of PowerShell – PowerShell 7». Microsoft. Retrieved 2019-06-01.
  99. ^ Lee, Steve (2019-03-28). «General Availability of PowerShell Core 6.2». devblogs.microsoft.com. Microsoft. Retrieved 2019-06-01.
  100. ^ Mackie, Kurt (2019-05-30). «Microsoft Releases PowerShell 7 Preview». 1105 Media Inc. Retrieved 2019-06-01.
  101. ^ Lee, Steve (2019-05-30). «PowerShell 7 Road Map». devblogs.microsoft.com. Microsoft. Retrieved 2020-08-12.
  102. ^ «PowerShell 7 Preview 5 | PowerShell». 23 October 2019. Archived from the original on 2020-02-15. Retrieved 2020-03-05.
  103. ^ «PowerShell 7.2 is the new version of Microsoft’s next-generation shell». itsfoss.net. 12 November 2021.
  104. ^ «Release v7.3.0 Release of PowerShell · PowerShell/PowerShell». GitHub. Archived from the original on 2022-11-09. Retrieved 2022-03-07.
  105. ^ «Test-Connection». PowerShell documentations. Microsoft. 9 August 2015.
  106. ^ «Tar and Curl Come to Windows! — Microsoft Tech Community — 382409». 22 March 2019. Archived from the original on 2020-09-11. Retrieved 2020-05-17.
  107. ^ Wheeler, Sean (2 June 2020). «About Scripts». Microsoft Docs. Microsoft.
  108. ^ Wheeler, Sean; Smatlak, David; Wilson, Chase (16 October 2019). «How to write a PowerShell module manifest». Docs. Microsoft.
  109. ^ Wheeler, Sean; Smatlak, David (22 November 2019). «How to Write a PowerShell Script Module». Microsoft Docs. Microsoft.
  110. ^ Wheeler, Sean (13 November 2016). «How to Write a PowerShell Binary Module». Microsoft Docs. Microsoft.
  111. ^ Wheeler, Sean; Jofre, Juan Pablo; Vorobev, Sergei; Nikolaev, Kirill; Coulter, David (2 June 2020). «About Types.ps1xml». Microsoft Docs. Microsoft.
  112. ^ Wheeler, Sean. «Export-Clixml». Microsoft Docs. Microsoft.
  113. ^ Wheeler, Sean; Jofre, Juan Pablo; Vorobev, Sergei; Nikolaev, Kirill; Coulter, David. «Export-Console». Microsoft Docs. Microsoft.
  114. ^ Wheeler, Sean (2 June 2020). «About Session Configuration Files». Microsoft Docs. Microsoft.
  115. ^ Wheeler, Sean (2 June 2020). «New-PSRoleCapabilityFile». Microsoft Docs. Microsoft.
  116. ^ «Microsoft Transporter Suite for Lotus Domino». Microsoft. Retrieved 2008-03-07.
  117. ^ «PowerTools for Open XML». Retrieved 2008-06-20.
  118. ^ «MO74: WebSphere MQ – Windows PowerShell Library». Retrieved 2007-12-05.
  119. ^ «IoT Core Add-ons command-line options». Retrieved 2020-06-13.
  120. ^ «PowerShell Commands for Active Directory by Quest Software». Retrieved 2008-07-02.
  121. ^ «PowerShell Remoting through Group Policy». Retrieved 2007-12-07.
  122. ^ «VMware vSphere PowerCLI». Retrieved 2014-09-09.
  123. ^ «Windows PowerShell : IIS7 PowerShell Provider Tech Preview 2». Retrieved 2008-07-03.
  124. ^ «Kudos to the Win7 Diagnostics Team». Retrieved 2009-06-15.
  125. ^ Michael, Niehaus (10 Jul 2009). «MDT 2010 New Feature #16: PowerShell support». Retrieved 2014-10-27.
  126. ^ «Kudos to NetApp for Data ONTAP PowerShell ToolKit». Retrieved 2010-06-15.
  127. ^ «PowerShell Toolkit 4.2 Announcement». 23 June 2016. Retrieved 2016-09-07.
  128. ^ «Heterogeneous Job Scheduling With PowerShell». Retrieved 2010-09-15.
  129. ^ «UIAutomation PowerShell Extensions». Retrieved 2012-02-16.
  130. ^ «EqualLogic HIT-ME with PowerShell». Retrieved 2012-03-09.
  131. ^ de:LOGINventory
  132. ^ «Selenium PowerShell eXtensions». Retrieved 2012-08-20.
  133. ^ «Pash». SourceForge. Dice Holdings, Inc. Retrieved 2011-09-27.
  134. ^ «Pash Project». GitHub. Retrieved 2013-04-10.
  135. ^ «Pash is now obsolete · Issue #429 · Pash-Project/Pash». GitHub. Retrieved 2019-11-26.

Further reading[edit]

  • Finke, Douglas (2012). Windows PowerShell for Developers. O’Reilly Media. ISBN 978-1-4493-2270-0.
  • Holmes, Lee (2006). Windows PowerShell Quick Reference. O’Reilly Media. ISBN 0-596-52813-2.
  • Holmes, Lee (2007). Windows PowerShell Cookbook. O’Reilly Media. ISBN 978-0-596-52849-2.
  • Jones, Don; Hicks, Jeffery (2010). Windows PowerShell 2.0: TFM (3rd ed.). Sapien Technologies. ISBN 978-0-9821314-2-8.
  • Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Self-published. ISBN 978-1-9536450-3-6.
  • Kopczynski, Tyson; Handley, Pete; Shaw, Marco (2009). Windows PowerShell Unleashed (2nd ed.). Pearson Education. ISBN 978-0-672-32988-3.
  • Kumaravel, Arul; White, Jon; Naixin Li, Michael; Happell, Scott; Xie, Guohui; Vutukuri, Krishna C. (2008). Professional Windows PowerShell Programming: Snapins, Cmdlets, Hosts and Providers. Wrox Press. ISBN 978-0-470-17393-0.
  • Oakley, Andy (2005). Monad (AKA PowerShell). O’Reilly Media. ISBN 0-596-10009-4.
  • Watt, Andrew (2007). Professional Windows PowerShell. Wrox Press. ISBN 978-0-471-94693-9.
  • Wilson, Ed (2013). Windows PowerShell 3.0 Step by Step. Microsoft Press. ISBN 978-0-7356-6339-8.
  • Wilson, Ed (2014). Windows PowerShell Best Practices. Microsoft Press. ISBN 978-0-7356-6649-8.

External links[edit]

Wikiversity has learning resources about PowerShell

  • Official website Edit this at Wikidata
  • PowerShell on GitHub
  • Windows PowerShell Survival Guide on TechNet Wiki

Главная / Операционные системы /
Командная строка и сценарии Windows / Тест 1

Упражнение 1:


Номер 1

В каких версиях операционной системы Windows можно пользоваться командными файлами?

Ответ:

(1) во всех версиях Windows 

(2) в Windows NT и выше 

(3) в Windows XP и выше 


Номер 2

Какие версии операционной системы Windows поддерживают сервер сценариев WSH?

Ответ:

(1) Windows 2000 и выше 

(2) все 32-разрядные версии Windows 

(3) Windows NT и выше 


Номер 3

Какие версии операционной системы Windows поддерживают оболочку PowerShell?

Ответ:

(1) Windows XP SP2 и выше 

(2) все 32-разрядные версии Windows 

(3) Windows 2000 и выше 


Упражнение 2:


Номер 1

Какие средства позволяют напрямую обращаться к объектам WMI?

Ответ:

(1) оболочка WMIC 

(2) сценарии WSH 

(3) интерпретатор Cmd.exe 


Номер 2

Какие средства позволяют напрямую обращаться к объектам .NET?

Ответ:

(1) оболочка WMIC 

(2) сценарии WSH 

(3) оболочка Windows PowerShell 


Номер 3

Какие средства позволяют обращаться к объектам WMI непосредственно из командной строки?

Ответ:

(1) оболочка WMIC 

(2) оболочка Windows PowerShell 

(3) интерпретатор Cmd.exe 


Упражнение 3:


Номер 1

Какие языки можно использовать для написания сценариев WSH?

Ответ:

(1) Microsoft VBScript 

(2) Microsoft JScript 

(3) Microsoft C# 


Номер 2

Можно ли написать сценарий WSH на языке Perl?

Ответ:

(1) нет 

(2) да, Perl поддерживается по умолчанию 

(3) да, но требуется установка специального модуля поддержки Perl 


Номер 3

Какие языки можно использовать для написания сценариев PowerShell?

Ответ:

(1) Microsoft VBScript 

(2) собственный язык Windows PowerShell 

(3) Microsoft C# 


Упражнение 4:


Номер 1

Какое средство автоматизации предлагает собственную объектную модель?

Ответ:

(1) Cmd.exe 

(2) Windows PowerShell 

(3) WSH 


Номер 2

Можно ли написать сценарий WSH на языке Python?

Ответ:

(1) нет 

(2) да, Python поддерживается по умолчанию 

(3) да, но только после установки модуля поддержки Python 


Номер 3

Какие средства позволяют обращаться к объектам COM непосредственно из командной строки?

Ответ:

(1) сценарии WSH 

(2) оболочка Windows PowerShell 

(3) интерпретатор Cmd.exe 


Упражнение 5:


Номер 1

Можно ли в Windows использовать стандартные Unix-утилиты?

Ответ:

(1) да, после установки пакета Services for Unix  

(2) да, Unix-утилиты поддерживаются по умолчанию 

(3) нельзя 


Номер 2

Какие средства позволяют управлять приложениями-серверами автоматизации?

Ответ:

(1) оболочка Windows PowerShell 

(2) сценарии WSH 

(3) оболочка Cmd.exe 


Номер 3

Какие средства позволяют управлять серверами автоматизации в интерактивном режиме?

Ответ:

(1) оболочка Windows PowerShell 

(2) сценарии WSH 

(3) оболочка Cmd.exe 


Упражнение 6:


Номер 1

Какие из средств автоматизации поддерживают работу в интерактивном режиме?

Ответ:

(1) WSH 

(2) WMIC  

(3) Windows PowerShell 


Номер 2

Какие из средств автоматизации являются оболочками командной строки?

Ответ:

(1) Cmd.exe 

(2) WSH  

(3) Windows PowerShell 


Номер 3

Какие средства автоматизации имеют встроенную справочную систему?

Ответ:

(1) интерпретатор Cmd.exe 

(2) WSH 

(3) Windows PowerShell 


Аннотация: Описываются возможности оболочки Windows PowerShell и отличие ее от традиционных оболочек и языков сценариев. Обсуждаются основные концепции PowerShell (типы команд, структура командлетов, псевдонимы команд). Рассматриваются особенности справочной системы PowerShell

Введение в оболочку командной строки Windows PowerShell

На настоящий момент мы рассмотрели уже три разных инструмента, предназначенных для автоматизации работы в операционной системе Windows: оболочки командной строки Cmd.exe и WMIC, а также сервер сценариев WSH. Зачем же компании Microsoft понадобилась разработка еще одной полностью новой оболочки командной строки со своим языком сценариев?

Причины и цели создания новой оболочки

Чтобы ответить на этот вопрос, вспомним основные требования к «идеальному» средству автоматизации, которые мы обсуждали в первой лекции, и посмотрим, в какой степени удовлетворяют этим требованиям перечисленные выше инструменты (табл.16.1).

Таблица
16.1.
Требования к инструменту автоматизации

Требование Cmd.exe WSH WMIC
Работа во всех версиях операционной системы без установки дополнительного программного обеспечения Да Да Нет (только Windows XP и выше)
Интеграция с командной строкой Да Нет Да
Согласованный и непротиворечивый синтаксис команд и утилит Нет Нет Да
Поддержка псевдонимов (кратких синонимов) для длинных названий команд Нет Нет Да
Автоматическое завершения команд и имен файлов при вводе их с клавиатуры Частично (автоматическое завершение имен файлов и папок) Нет Нет
Поддержка истории введенных команд с возможностью их повторного вызова, просмотра и редактирования Да Нет Да
Наличие подробной встроенной справки по командам с примерами использования Частично Нет Да
Возможность автоматического выполнения сценариев Да (язык командных файлов) Да (языки сценариев VBScript, JScript и т.д.) Частично (команды WMIC можно встраивать в командные файлы)
Доступ и использование всех технологий и возможностей, поддерживаемых операционной системой Нет (нет прямого доступа к объектам COM, WMI, ADSI, .NET) Да Нет (доступ только к объектам WMI)

Как мы видим, у каждого из рассмотренных нами ранее инструментов автоматизации присутствовали довольно серьезные недостатки, не позволявшие сказать, что Windows обладает по-настоящему мощным и эффективным средством для работы с командной строкой и написания сценариев.

Новая оболочка Windows PowerShell (предварительно она была названа Monad) была задумана разработчиками Microsoft как более мощная среда для написания сценариев и работы из командной строки. Разработчики PowerShell преследовали несколько целей. Главная и самая амбициозная из них – создать среду составления сценариев, которая наилучшим образом подходила бы для современных версий операционной системы Windows и была бы более функциональной, расширяемой и простой в использовании, чем какой-либо аналогичный продукт для любой другой операционной системы. В первую очередь эта среда должна была подходить для решения задач, стоящих перед системными администраторами (тем самым Windows получила бы дополнительное преимущество в борьбе за сектор корпоративных платформ), а также удовлетворять требованиям разработчиков программного обеспечения, предоставляя им средства для быстрой реализации интерфейсов управления к создаваемым приложениям.

Для достижения этих целей были решены следующие задачи:

  • Обеспечение прямого доступа из командной строки к объектам COM, WMI и .NET. В новой оболочке присутствуют команды, позволяющие в интерактивном режиме работать с COM-объектами, а также с экземплярами классов, определенных в информационных схемах WMI и .NET.
  • Организация работы с произвольными источниками данных в командной строке по принципу файловой системы. Например, навигация по системному реестру или хранилищу цифровых сертификатов выполняется из командной строки с помощью аналога команды CD интерпретатора Cmd.exe.
  • Разработка интуитивно понятной унифицированной структуры встроенных команд, основанной на их функциональном назначении. В новой оболочке имена всех внутренних команд (в PowerShell они называются командлетами) соответствуют шаблону «глагол-существительное», например, Get-Process (получить информацию о процессе), Stop-Service (остановить службу), Clear-Host (очистить экран консоли) и т.д. Для одинаковых параметров внутренних команд используются стандартные имена, структура параметров во всех командах идентична, все команды обрабатываются одним синтаксическим анализатором. В результате облегчается запоминание и изучение команд.
  • Обеспечение возможности расширения встроенного набора команд. Внутренние команды PowerShell могут дополняться командами, создаваемыми пользователем. При этом они полностью интегрируются в оболочку, информация о них может быть получена из стандартной справочной системы PowerShell.
  • Организация поддержки знакомых команд из других оболочек. В PowerShell на уровне псевдонимов собственных внутренних команд поддерживаются наиболее часто используемые стандартные команды из оболочки Cmd.exe и Unix-оболочек. Например, если пользователь, привыкший работать с Unix-оболочкой, выполнит ls, то он получит ожидаемый результат: список файлов в текущем каталоге (то же самое относится к команде dir).
  • Разработка полноценной встроенной справочной системы для внутренних команд. Для большинства внутренних команд в справочной системе дано подробное описание и примеры использования. В любом случае встроенная справка по любой внутренней команде будет содержать краткое описание всех ее параметров.
  • Реализация автоматического завершения при вводе с клавиатуры имен команд, их параметров, а также имен файлов и папок. Данная возможность значительно упрощает и ускоряет ввод команд с клавиатуры.

Главной особенностью среды PowerShell, отличающей ее от всех других оболочек командной строки, является то, что единицей обработки и передачи информации здесь является объект, а не строка текста.

Отличие PowerShell от других оболочек – ориентация на объекты

При разработке любого языка программирования одним из основных является вопрос о том, какие типы данных и каким образом будут в нем представлены. При создании PowerShell разработчики решили не изобретать ничего нового и воспользоваться унифицированной объектной моделью .NET. Данный выбор был сделан по нескольким причинам.

Во-первых, платформа .NET повсеместно используется при разработке программного обеспечения для Windows и представляет, в частности, общую информационную схему, с помощью которой разные компоненты операционной системы могут обмениваться данными друг с другом.

Во-вторых, объектная модель .NET является самодокументируемой: каждый объект .NET содержит информацию о своей структуре. При интерактивной работе это очень полезно, так как появляется возможность непосредственно из командной строки выполнить запрос к определенному объекту и увидеть описание его свойств и методов, то есть понять, какие именно манипуляции можно проделать с данным объектом, не изучая дополнительной документации с его описанием.

В-третьих, работая в оболочке с объектами, можно с помощью их свойств и методов легко получать нужные данные, не занимаясь разбором и анализом символьной информации, как это происходит во всех традиционных тексто-ориентированных оболочках командной строки. Рассмотрим пример. В Windows XP есть консольная утилита tasklist.exe, которая выдает информацию о процессах запущенных в системе:

C:>tasklist

Имя образа                   PID Имя сессии       № сеанса       Память
========================= ====== ================ ======== ============
System Idle Process            0                         0        16 КБ
System                         4                         0        32 КБ
smss.exe                     560                         0        68 КБ
csrss.exe                    628                         0     4 336 КБ
winlogon.exe                 652                         0     3 780 КБ
services.exe                 696                         0     1 380 КБ
lsass.exe                    708                         0     1 696 КБ
svchost.exe                  876                         0     1 164 КБ
svchost.exe                  944                         0     1 260 КБ
svchost.exe                 1040                         0    10 144 КБ
svchost.exe                 1076                         0       744 КБ
svchost.exe                 1204                         0       800 КБ
spoolsv.exe                 1296                         0     1 996 КБ
kavsvc.exe                  1516                         0     9 952 КБ
klnagent.exe                1660                         0     5 304 КБ
klswd.exe                   1684                         0        64 КБ

Предположим, что мы в командном файле интерпретатора Cmd.exe с помощью этой утилиты хотим определить, сколько оперативной памяти тратит процесс kavsvc.exe. Для этого нужно выделить из выходного потока команды tasklist соответствующую строку, извлечь из нее подстроку, содержащую нужное число и убрать пробелы между разрядами (при этом следует учесть, что в зависимости от настроек операционной системы разделителем разрядов может быть не пробел, а другой символ). В PowerShell аналогичная задача решается с помощью команды get-process, которая возвращает коллекцию объектов, каждый из которых соответствует одному запущенному процессу. Для определения памяти, затрачиваемой процессом kavsvc.exe, нет необходимости в дополнительных манипуляциях с текстом, достаточно просто взять значение свойства WS объекта, соответствующего данному процессу.

Наконец, объектная модель .NET позволяет PowerShell напрямую использовать функциональность различных библиотек, являющихся частью платформы .NET. Например, чтобы узнать, каким днем недели было 9 ноября 1974 года, в PowerShell можно выполнить следующую команду:

(get-date "09.11.1974").DayOfWeek

В этом случае команда get-date возвращает .NET-объект DateTime, имеющий свойство, при обращении к которому вычисляется день недели для соответствующей даты. Таким образом, разработчикам PowerShell не нужно создавать специальную библиотеку для работы с датами и временем – они просто берут готовое решение в .NET.

Загрузка и установка PowerShell

Оболочка PowerShell может работать не во всех версиях операционной системы, ее можно использовать в Windows XP SP 2, Windows Server 2003 SP 1 и более поздних версиях. Кроме этого, в системе должна быть установлена платформа .NET Framework 2.0 (в Windows XP данную среду придется устанавливать дополнительно, дистрибутив можно загрузить с сайта Microsoft по адресу http://msdn.microsoft.com/netframework/downloads/updates/default.aspx).

Загрузить PowerShell можно с сайта Microsoft, открыв страницу http://microsoft.com/powershell, где имеются ссылки на файл установки последней версии и пакеты документации на разных языках. Запустив загруженный файл, следуйте указаниям мастера установки. В 32-разрядных версиях Windows оболочка PowerShell устанавливается по умолчанию в каталог %SystemRoot%System32WindowsPowerShellv1.0. В 64-разрядных версиях Windows 32-разрядная версия PowerShell устанавливается в каталог %SystemRoot%SystemWow64WindowsPowerShellv1.0, а 64-разрядная версия Windows PowerShell устанавливается в каталог %SystemRoot%System32WindowsPowerShellv1.0.

Запуск оболочки. Выполнение команд

Установив оболочку в системе, можно начать новый интерактивный сеанс. Для этого следует нажать на кнопку Пуск (Start), открыть меню Все программы (All Programs) и выбрать элемент Windows PowerShell. Другой вариант запуска оболочки – пункт Выполнить… (Run) в меню Пуск (Start), ввести имя файла powershell и нажать кнопку OK.

В результате откроется новое командное окно с приглашением вводить команды (рис. 16.1).

Выполним первую команду в PowerShell. Пусть это будет что-то знакомое, например dir (команды в PowerShell обрабатываются без учета регистра). На экран будет выведен список файлов в текущем каталоге:

PS C:Documents and SettingsUser> dir
    Каталог: Microsoft.PowerShell.CoreFileSystem::C:Documents 
      and SettingsUser
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d---s        14.12.2007     10:10            Cookies
d----        12.05.2005     17:16            DoctorWeb
d----        06.11.2004     13:03            Phone Browser
d---s        22.09.2004     23:49            UserData
d-r--        04.10.2004     15:33            Главное меню
d-r--        05.12.2007      0:49            Избранное
d-r--        31.10.2007     21:03            Мои документы
d----        05.12.2007     10:54            Рабочий стол
-a---        24.05.2006     21:22       8304 gsview32.ini

Типы команд PowerShell

В оболочке PowerShell поддерживаются команды четырех типов: командлеты, функции, сценарии и внешние исполняемые файлы.

Первый тип – так называемые командлеты (cmdlet). Этот термин используется пока только внутри PowerShell. Командлет представляет собой класс .NET, порожденный от базового класса Cmdlet ; разрабатываются командлеты с помощью пакета PowerShell Software Developers Kit (SDK). Единый базовый класс Cmdlet гарантирует совместимый синтаксис всех командлетов, а также автоматизирует анализ параметров командной строки и описание синтаксиса командлетов для встроенной справки.

Данный тип команд компилируется в динамическую библиотеку (DLL) и подгружается к процессу PowerShell во время запуска оболочки (то есть сами по себе командлеты не могут быть запущены как приложения, но в них содержатся исполняемые объекты). Так как компилированный код подгружается к процессу оболочки, данный тип команд выполняется наиболее эффективно. Командлеты – это аналог внутренних команд традиционных оболочек.

Следующий тип команд – функции. Функция – это блок кода на языке PowerShell, имеющий название и находящийся в памяти до завершения текущего сеанса командной оболочки. Функции, как и командлеты, поддерживают именованные параметры. Анализ синтаксиса функции производится один раз при ее объявлении.

Сценарий – это блок кода на языке PowerShell, хранящийся во внешнем файле с расширением ps1. Анализ синтаксиса сценария производится при каждом его запуске.

Последний тип команд – внешние исполняемые файлы, которые выполняются обычным образом операционной системой.

Содержание

  1. Установка Windows PowerShell Installing Windows PowerShell
  2. Поиск PowerShell в Windows 10, 8.1, 8.0 и 7 Finding PowerShell in Windows 10, 8.1, 8.0, and 7
  3. Консоль For Console
  4. ISE For ISE
  5. Поиск PowerShell в версиях Windows Server Finding PowerShell in Windows Server versions
  6. Выпуски Windows Server Core Windows Server Core editions
  7. Выпуски Windows Server Desktop Windows Server Desktop editions
  8. Проверка версии PowerShell How to check the version of PowerShell
  9. Обновление существующей версии Windows PowerShell Upgrading existing Windows PowerShell
  10. Необходимость Azure PowerShell Need Azure PowerShell
  11. Основы Windows PowerShell
  12. Что способствовало появлению Windows PowerShell?
  13. Что такое Windows PowerShell?
  14. Версии Windows PowerShell
  15. Язык PowerShell
  16. Оболочка Windows PowerShell
  17. Командлеты в PowerShell
  18. Конвейер в PowerShell
  19. Фоновое исполнение заданий
  20. Удаленное управление на PowerShell
  21. Сценарии, функции и модули в Windows PowerShell
  22. Интегрированная среда сценариев Windows PowerShell (ISE)

Установка Windows PowerShell Installing Windows PowerShell

Windows PowerShell установлен по умолчанию в каждой ОС Windows, начиная с Windows 7 с пакетом обновления 1 (SP1) и Windows Server 2008 R2 с пакетом обновления 1 (SP1). Windows PowerShell comes installed by default in every Windows, starting with Windows 7 SP1 and Windows Server 2008 R2 SP1.

Если вас интересует PowerShell версии 6 или более поздней, вам нужно установить PowerShell Core вместо Windows PowerShell. If you are interested in PowerShell 6 and later, you need to install PowerShell Core instead of Windows PowerShell. Дополнительные сведения см. в статье Установка PowerShell Core в Windows. For that, see Installing PowerShell Core on Windows.

Поиск PowerShell в Windows 10, 8.1, 8.0 и 7 Finding PowerShell in Windows 10, 8.1, 8.0, and 7

Иногда найти консоль или ISE (интегрированную среду сценариев) PowerShell в Windows бывает непросто, так как их расположение в разных версиях Windows отличается. Sometimes locating PowerShell console or the Integrated Scripting Environment (ISE) in Windows can be difficult, as its location moves from one version of Windows to the next.

Следующие таблицы помогут найти PowerShell в вашей версии Windows. The following tables should help you find PowerShell in your Windows version. Все указанные версии являются оригинальными, сразу после выпуска и без обновлений. All versions listed here are the original version, as released, with no updates.

Консоль For Console

Версия Version Location Location
Windows 10 Windows 10 Щелкните значок Windows в левом нижнем углу и начните вводить PowerShell. Click left lower corner Windows icon, start typing PowerShell
Windows 8.1, 8.0 Windows 8.1, 8.0 На начальном экране начните вводить PowerShell. On the start screen, start typing PowerShell.
Если вы находитесь на рабочем столе, щелкните значок Windows в левом нижнем углу и начните вводить PowerShell. If on desktop, click left lower corner Windows icon, start typing PowerShell
Windows 7 с пакетом обновления 1 (SP1) Windows 7 SP1 Щелкните значок Windows в левом нижнем углу и в поле поиска начните вводить PowerShell. Click left lower corner Windows icon, on the search box start typing PowerShell

ISE For ISE

Версия Version Location Location
Windows 10 Windows 10 Щелкните значок Windows в левом нижнем углу и начните вводить ISE. Click left lower corner Windows icon, start typing ISE
Windows 8.1, 8.0 Windows 8.1, 8.0 На начальном экране введите PowerShell ISE. On the start screen, type PowerShell ISE.
Если вы находитесь на рабочем столе, щелкните значок Windows в левом нижнем углу и введите PowerShell ISE. If on desktop, click left lower corner Windows icon, type PowerShell ISE
Windows 7 с пакетом обновления 1 (SP1) Windows 7 SP1 Щелкните значок Windows в левом нижнем углу и в поле поиска начните вводить PowerShell. Click left lower corner Windows icon, on the search box start typing PowerShell

Поиск PowerShell в версиях Windows Server Finding PowerShell in Windows Server versions

Начиная с Windows Server 2008 R2, операционную систему Windows можно установить без графического пользовательского интерфейса (GUI). Starting with Windows Server 2008 R2, Windows operating system can be installed without the graphical user interface (GUI). Выпуски Windows Server без GUI называются выпусками Core , а выпуски с GUI — Desktop. Editions of Windows Server without GUI are named Core editions, and editions with the GUI are named Desktop.

Выпуски Windows Server Core Windows Server Core editions

Во всех выпусках Core при входе на сервер открывается окно командной строки Windows. In all Core editions, when you log to the server you get a Windows command prompt window.

Введите powershell и нажмите клавишу ВВОД , чтобы запустить PowerShell в сеансе командной строки. Type powershell and press ENTER to start PowerShell inside the command prompt session. Введите exit , чтобы завершить сеанс PowerShell и вернуться к командной строке. Type exit to terminate the PowerShell session and return to command prompt.

Выпуски Windows Server Desktop Windows Server Desktop editions

Во всех выпусках Desktop нужно щелкнуть значок Windows в левом нижнем углу и начать вводить PowerShell. In all desktop editions, click the left lower corner Windows icon, start typing PowerShell. Появятся параметры консоли и ISE. You get both console and ISE options.

Единственное исключение из этого правила — ISE в Windows Server 2008 R2 с пакетом обновления 1 (SP1). В этом случае щелкните значок Windows в левом нижнем углу и введите PowerShell ISE. The only exception to the above rule is the ISE in Windows Server 2008 R2 SP1; in this case, click the left lower corner Windows icon, type PowerShell ISE.

Проверка версии PowerShell How to check the version of PowerShell

Чтобы узнать, какая версия PowerShell установлена, запустите консоль PowerShell (или ISE), введите $PSVersionTable и нажмите клавишу ВВОД. To find which version of PowerShell you have installed, start a PowerShell console (or the ISE) and type $PSVersionTable and press ENTER. Найдите значение PSVersion . Look for the PSVersion value.

Обновление существующей версии Windows PowerShell Upgrading existing Windows PowerShell

В пакет установки для PowerShell входит установщик WMF. The installation package for PowerShell comes inside a WMF installer. Версия установщика WMF совпадает с версией PowerShell. Для Windows PowerShell нет отдельного установщика. The version of the WMF installer matches the version of PowerShell; there’s no stand alone installer for Windows PowerShell.

Если вам нужно обновить существующую версию PowerShell, в Windows используйте следующую таблицу, чтобы найти установщик для нужной версии PowerShell. If you need to update your existing version of PowerShell, in Windows, use the following table to locate the installer for the version of PowerShell you want to update to.

Windows Windows PS 3.0 PS 3.0 PS 4.0 PS 4.0 PS 5.0 PS 5.0 PS 5.1 PS 5.1
Windows 10 (см. примечание 1) Windows 10 (see Note1)
Windows Server 2016 Windows Server 2016
установлено installed
Windows 8.1 Windows 8.1
Windows Server 2012 R2 Windows Server 2012 R2
установлено installed WMF 5.0 WMF 5.0 WMF 5.1 WMF 5.1
Windows 8 Windows 8
Windows Server 2012 Windows Server 2012
установлено installed WMF 4.0 WMF 4.0 WMF 5.0 WMF 5.0 WMF 5.1 WMF 5.1
Windows 7 с пакетом обновления 1 (SP1) Windows 7 SP1
Windows Server 2008 R2 с пакетом обновления 1 (SP1) Windows Server 2008 R2 SP1
WMF 3.0 WMF 3.0 WMF 4.0 WMF 4.0 WMF 5.0 WMF 5.0 WMF 5.1 WMF 5.1

Если в начальном выпуске Windows 10 включены автоматические обновления, PowerShell обновляется с версии 5.0 до 5.1. On the initial release of Windows 10, with automatic updates enabled, PowerShell gets updated from version 5.0 to 5.1. Если оригинальная версия Windows 10 не обновлена в Центре обновления Windows, версия PowerShell будет 5.0. If the original version of Windows 10 is not updated through Windows Updates, the version of PowerShell is 5.0.

Необходимость Azure PowerShell Need Azure PowerShell

Если вы ищете Azure PowerShell , можно начать с раздела Общие сведения об Azure PowerShell. If you’re looking for Azure PowerShell , you could start with Overview of Azure PowerShell.

Основы Windows PowerShell

В данной статье мы рассмотрим такую технологию от компании Microsoft как Windows PowerShell, мы поговорим о том, что такое PowerShell, что такое командлеты и конвейер, как писать сценарии и модули, а также затронем другие не менее важные и полезные возможности Windows PowerShell.

Что способствовало появлению Windows PowerShell?

До появления PowerShell существовали (и существуют) следующие инструменты для автоматизации и администрирования сервисов: командная строка Windows и Windows Script Host. Но у этих технологий есть недостатки.

У командной строки Windows есть и возможность выполнять какие-то административные задачи и возможность записать алгоритм действий, сохранив его в виде скрипта (bat-файла), при этом можно использовать некие элементы программирования, например, использовать переменные, условные конструкции и даже что-то вроде циклов.

Большинство программных продуктов имеет консольный интерфейс, т.е. мы можем управлять программой, используя командную строку, при этом экономя ресурсы за счет отсутствия затрат на работу графического интерфейса. Компания Microsoft для серверной операционной системы Windows Server даже выпускает редакции без графического интерфейса (Server Core, в Windows Server 2019), но всего этого недостаточно, так как возможности командной строки ограничены, т.е. написать какую-то сложную логику для автоматизации чего-либо мы не сможем, а если и сможем, то на это нам потребуется время и знания.

Также недостатком командной строки является то, что для полноценного управления сервером мы используем различные консольные утилиты программных продуктов, и поэтому использовать командную строку для администрирования на самом деле сложно, с точки зрения того, что у всех этих утилит разный синтаксис, параметры, методы использования и для того чтобы выполнять типовые задачи, т.е. каждодневные, приходиться держать все это в памяти, а для выполнения нетиповых задач приходиться сначала почитать справку или документацию.

Технология Windows Script Host позволяет выполнять все административные задачи, что и командная строка, включая их автоматизацию путем написания WSH скриптов, но здесь мы уже можем использовать полноценные языки программирования (VBScript и JScript), т.е. можно реализовывать сложную логику и алгоритмы. К тому же с помощью WSH мы управляем программными продуктами через объектный интерфейс, другими словами Windows Script Host намного «круче» чем командная строка. Но данная технология также не стала тем идеальным инструментом администрирования и автоматизации этого администрирования для системных администраторов, так как Windows Script Host требовал знаний вышеперечисленных языков программирования, что для системных администраторов на самом деле лишнее. Администраторам нужно всего лишь простой инструмент администрирования с возможностью запрограммировать какие-то действия, а углубляться в объектные модели программных продуктов на языках программирования VBScript и JScript им не хочется.

В итоге компании Microsoft необходимо было разработать такой инструмент администрирования для системных администраторов, который бы на 100 процентов удовлетворял все потребности сисадминов как в плане возможностей администрирования и автоматизации, так и в плане удобства и простоты использования, таким образом, появился Windows PowerShell.

Что такое Windows PowerShell?

Windows PowerShell – это язык сценариев и командная оболочка Windows, которые разработаны для администрирования и конфигурирования операционных систем Windows.

PowerShell разработан на основе среды CRL и платформы .NET Framework и в отличие от командной строки, которая принимает и возвращает текст, Windows PowerShell работает с объектами. У каждого объекта в PowerShell есть свойства и методы, которые можно использовать для управления этими объектами.

В Windows PowerShell Microsoft разработала концепцию командлетов (cmdlets), которая представляет собой систему именования команд «Глагол-Существительное». Данная система позволяет системным администраторам быстрей освоить и упростить работу с PowerShell.

С помощью Windows PowerShell можно:

  • Получать доступ к файловой системе;
  • Управлять реестром;
  • Управлять службами;
  • Управлять процессами;
  • Настраивать операционную систему;
  • Устанавливать программное обеспечение;
  • Устанавливать роли и компоненты сервера;
  • Осуществлять администрирование и конфигурирование ролей и компонентов сервера;
  • Писать и использовать сценарии для автоматизации управления и администрирования;
  • Выполнять другие задачи системных администраторов.

Windows PowerShell содержит многие часто используемые утилиты и команды, запускаемые из командной строки, например ipconfig, ping и другие. Сделано это для того, чтобы облегчить переход системных администраторов с командной строки на PowerShell.

Также для удобства многие часто используемые команды и утилиты в PowerShell имеют синонимы (Alias), например cls — это синоним командлета Clear-Host, dir синоним Get-ChildItem (полный список синонимов можно посмотреть путем запуска командлета Get-Alias).

Для упрощения поиска нужной команды в PowerShell есть специальный командлет Get-Command, с помощью которого можно осуществлять поиск, как по глаголу, так и по существительному. Все команды в Windows PowerShell сгруппированы в модули (например, Hyper-V, NetTCPIP), что также упрощает поиск нужной команды.

После того как нужная команда найдена, можно посмотреть инструкцию по работе с этой командой, т.е. справку, для этих целей есть специальный командлет Get-Help, например следующая команда покажет справку по командлету Get-Command:

Справка в Windows PowerShell может быть краткой, детальной (параметр -Detailed), полной (параметр -Full), а также можно выводить только примеры (параметр — Examples). Следующая команда покажет только примеры использования командлета Get-Command:

Справка PowerShell обновляемая, т.е. ее можно обновить командой Update-Help.

Версии Windows PowerShell

Первая версия PowerShell 1.0 появилась 14 ноября 2006 года и выпускалась в виде отдельного дистрибутива, который можно было установить на следующие версии операционных систем Windows: Windows XP Service Pack 2, Windows Server 2003 Service Pack 1 и Windows Vista.

В Windows Server 2008 PowerShell 1.0 поставлялся в виде компонента, который также нужно было устанавливать.

Начиная с Windows 7 и Windows Server 2008 R2, PowerShell поставляется как неотъемлемый компонент системы (т.е. предустановленный, устанавливать его не надо). Ниже представлена таблица соответствия версии PowerShell и версии операционной системы Windows (т.е. какая версия PowerShell по умолчанию установлена в той или иной версии Windows):

Версия PowerShell Версии Windows
PowerShell 2.0 Windows 7, Windows Server 2008 R2
PowerShell 3.0 Windows 8, Windows Server 2012
PowerShell 4.0 Windows 8.1, Windows Server 2012 R2
PowerShell 5.0 Windows 10, Windows Server 2016

С каждой новой версией PowerShell становится все более мощным инструментом администрирования, для сравнения в первой PowerShell было около 130 командлетов, а в PowerShell 5.0 их уже более 600!

Узнать текущую версию PowerShell можно с помощью свойства PSVersion встроенной переменной $PSVersionTable, например, выполните следующую команду:

Или запустите командлет

где, значение PSVersion и будет версией PowerShell.

Язык PowerShell

PowerShell – это объектно-ориентированный скриптовой язык программирования.

Он используется для написания команд управления всеми компонентами операционной системы Windows в оболочке Windows PowerShell, а также для написания сценариев автоматизации задач администрирования в интегрированной среде сценариев Windows PowerShell (ISE). Язык PowerShell хоть и создан для задач администрирования, он является полноценным скриптовым языком программирования, так как имеет программные конструкции, которые присутствуют в каждом языке программирования, такие как: условия, циклы, обработка ошибок, работа с переменными, объектами, массивами.

Язык PowerShell имеет единый синтаксис написания команд и структуру именования этих команд по принципу «Глагол-Существительное», что делает данный язык интуитивно понятным как для программистов, так и для системных администраторов.

Более подробно о программировании на данном языке можете посмотреть в материале — Программирование на языке PowerShell.

Оболочка Windows PowerShell

Оболочка Windows PowerShell – это среда выполнения команд и сценариев на языке PowerShell.

Данная оболочка имеет те же возможности что и командная строка такие как: хранение истории выполнения команд, настройка внешнего вида оболочки, завершение выполнения команд сочетанием клавиш Ctrl+C, а также много других возможностей, которых нет в оболочке командной строки, например такая замечательная возможность как «подсветка синтаксиса» (появилась в PowerShell 5.0).

Запустить оболочку PowerShell можно несколькими способами, например:

  • Из командной строки, набрав PowerShell;
  • Через диалоговое окно «Выполнить» (сочетание клавиш Win+R), также набрав PowerShell;
  • В Windows 7 — Пуск->Все программы ->Стандартные ->Windows PowerShell -> Windows PowerShell;
  • В Windows 8.1 или Windows Server 2012 R2 — Пуск->Все программы ->Служебные ->Windows PowerShell;
  • В Windows 10 или Windows Server 2016 — Пуск->Все программы -> Каталог Windows PowerShell (в группе W) -> Windows PowerShell.

Пример запуска PowerShell в Windows Server 2016

Скриншот оболочки PowerShell в Windows Server 2016

Командлеты в PowerShell

Командлет (cmdlet) – это команда Windows PowerShell, с помощью которой можно осуществлять взаимодействие с объектами операционной системы с целью их управления.

Данные команды являются частью языка PowerShell. Командлеты построены по принципу «Глагол-Существительное», разделенные дефисом (-); другими словами, мы сначала указываем, что делать, а через дефис — над чем. Например, командлет Get-Help, где Get — это глагол, означающий «Получить», а Help — существительное «Помощь» в контексте PowerShell «Показать – Справку». Командлеты PowerShell возвращают результаты в виде объектов, что является одним из главных отличий от командной строки Windows, в которой команды возвращают только текст на экран.

Кроме командлетов на получение данных (Get), существуют и такие типы командлетов как:

  • Add – добавление данных;
  • Clear – очистить;
  • Enable – включить;
  • Disable – выключить;
  • New – создать;
  • Remove – удалить;
  • Set – задать;
  • Start — запустить;
  • Stop – остановить;
  • Export – экспортировать;
  • Import – импортировать;
  • И еще много других.

Полный список командлетов в Windows PowerShell можно посмотреть с помощью специального командлета Get-Command. Например, запустите его с параметром -CommandType cmdlet, в итоге на экране у Вас отобразится список командлетов.

Как Вы уже поняли, у командлетов есть параметры, с помощью которых мы можем конкретизировать действия командлета. Параметры бывают обязательные и необязательные, например, у командлета Get-Command обязательных параметров нет.

Ниже на картинке представлен способ поиска командлета по глаголу (параметр Verb). В данном случае у нас отобразился список командлетов, которые умеют что-то перезапускать.

Для поиска командлета по существительному необходимо использовать параметр Noun. Например, ниже мы получили список командлетов, которые работают со службами.

Если Вы не нашли нужный командлет по полному названию можете использовать маску в формате *Текст*.

Конвейер в PowerShell

Одной из главных возможностей Windows PowerShell является возможность использования конвейера при выполнении команд.

Конвейер – это передача результата работы командлета через вертикальную черту (|) другому командлету.

При этом, как Вы помните, в PowerShell командлеты работают с объектами и возвращают объекты, соответственно по конвейеру передаются также объекты.

С помощью конвейера можно выполнять сложные задачи простым и удобным способом без необходимости написания сложных алгоритмов и сценариев.

Например, давайте узнаем название самого большого файла в каталоге «C:WindowsSystem32» (простой пример конвейера).

  • Get-ChildItem – командлет получения объектов в указанном каталоге;
  • Sort-Object – командлет для сортировки объектов, в нашем случае мы сортируем по размеру файла (length -Descending);
  • Select-Object – командлет выбора нужных свойств объекта, в нашем случае мы выводим стандартные поля и только самый первый объект, т.е. большой файл (параметр -First 1).

Все командлеты отделены друг от друга вертикальной чертой. Результат работы каждого командлета передается на вход другому командлету, т.е. сначала мы получаем все объекты в указанном каталоге, затем сортируем полученный результат и в заключение выбираем самый первый объект.

Фоновое исполнение заданий

В Windows PowerShell есть возможность фонового исполнения заданий, она представляет собой механизм, с помощью которого можно запустить на выполнение команду (например, которая долго выполняется) в фоновом режиме, т.е. после запуска Вы возвращаетесь в текущую сессию и можете продолжить работу, не дожидаясь окончания работы команды. Данная возможность Вам понадобится тогда, когда у Вас возникнет необходимость запустить команду, работа которой занимает достаточно продолжительное время, а как Вы знаете, в течение этого времени сессия оболочки PowerShell блокируется до завершения работы команды, а Вам нужно продолжать работать.

Всеми заданиями, которые запущенны в фоновом режиме, Вы можете управлять, например, посмотреть список заданий, остановить работу задания, удалить задание, и, конечно же, посмотреть результат работы задания.

В Windows PowerShell для работы с фоновыми заданиями есть следующие командлеты:

  • Start-Job – запустить фоновую задачу;
  • Stop-Job – остановить фоновую задачу
  • Get-Job – посмотреть список фоновых задач;
  • Receive-Job – посмотреть результат выполнения фоновой задачи;
  • Remove-Job – удалить фоновую задачу;
  • Wait-Job – перевести фоновую задачу на передний план, для того чтобы дожидаться ее окончания.

Для запуска в фоновом режиме необходимо написать команду Start-Job, а в фигурных скобках <> команду или набор команд, которые необходимо выполнить в фоновом режиме.

Например, давайте запустим какую-нибудь задачу (показать список служб) в фоновом режиме, затем посмотрим на список фоновых заданий и выведем на экран результат работы нашего задания (т.е. список служб).

Запуск задачи в фоновом режиме

Смотрим на список задач запущенных в фоновом режиме

Отображаем результат работы задания Job1

Как видим, у нас появилась задача со статусом «Completed», т.е. она уже выполнилась (просто Get-Service отрабатывает быстро).

Для того чтобы посмотреть результат работы фоновой задачи, т.е. командлета Get-Service, мы выполнили команду Receive-Job и передали ей имя задания (можно и значение идентификатора). В результате у нас отобразился список служб.

Удаленное управление на PowerShell

Windows PowerShell рассчитан не только на локальное использование, но и на удаленное выполнение команд. Данная возможность необходима, чтобы Вы могли со своего рабочего места управлять удаленными компьютерами, т.е. выполнять команды PowerShell.

Существует несколько способов удаленного управления:

  • С помощью параметра –ComputerName (есть у многих команд). Другими словами Вы передаете имя компьютера, на котором необходимо выполнить команду, в качестве параметра. Способ обладает недостатком, так как ограничивается выполнением одной команды;
  • С помощью сессий. Командлет Enter-PSSession (интерактивный сеанс). Таким способом Вы подключаетесь к удаленному компьютеру и все команды, которые Вы будете набирать в оболочке PowerShell, будут выполняться на удаленном компьютере так же, как если бы Вы набирали команды непосредственно на удаленном компьютере. Способ также обладает недостатком, так как сеанс ограничивается одним компьютером;
  • С помощью командлета Invoke-Command. С помощью данного способа можно выполнять команды или сценарии как на одном компьютере, так и на нескольких.

Например, чтобы подключиться к удаленному компьютеру (в примере ниже ServerName) интерактивным сеансом выполните следующую команду:

Сценарии, функции и модули в Windows PowerShell

Если Вы написали некий алгоритм, скорей всего Вы захотите сохранить его, для того чтобы в дальнейшем им пользоваться. В Windows PowerShell для этих целей существует механизм использования сценариев.

Суть данного механизма следующая, Вы пишите нужный Вам набор команд и сохраняете его в качестве сценария — это простой текстовый файл с расширением .PS1.

Затем, для того чтобы выполнить этот сценарий, Вы просто запускаете его в оболочке PowerShell. При этом Вам необходимо либо указать полный путь к файлу сценария, либо перейти в каталог со сценарием и вызвать его по имени.

Важно!

По умолчанию выполнение сценариев в Windows запрещено! Для того чтобы посмотреть политику выполнения сценариев выполните командлет Get-ExecutionPolicy. В результате он вернет действующую политику, например:

  • Restricted – блокируется выполнение любых сценариев (значение по умолчанию);
  • AllSigned – разрешено выполнение сценариев, которые имеют цифровую подпись;
  • RemoteSigned – разрешено выполнение локальных сценариев, все скачанные сценарии должны иметь цифровую подпись;
  • Unrestricted — разрешено выполнение любых сценариев (не рекомендуется, так как небезопасно!).

Для разрешения выполнения сценариев необходимо использовать командлет Set-ExecutionPolicy с одним из вышеперечисленных параметров.

Например, для разрешения выполнения локальных сценариев выполним следующую команду, и согласимся с внесением изменений, нажав Y.

В сценарии можно передавать параметры, делать их обязательными или задавать значение по умолчанию.

В Windows PowerShell предусмотрен механизм создания собственных функций, которые также как и встроенные командлеты можно будет использовать в оболочке PowerShell.

Для этого необходимо указать ключевое слово Function и затем в фигурных скобках <> написать алгоритм работы этой функции, т.е. набор команд (например, какая-нибудь часто используемая процедура: создать пользователя с определенными правами, очистить определенные каталоги и так далее). Потом необходимо сохранить все это в сценарий, но только уже с расширением .psm1, так как этот файл будет являться уже модулем.

Это еще не все, этот файл необходимо поместить в каталог, в котором PowerShell ищет модули. Таких каталогов несколько (специальный каталог в профиле пользователя, каталог, где установлен PowerShell), их можно посмотреть в переменных окружения PowerShell. Для этого выполните следующую команду

После того как Вы поместите написанный Вами модуль в специальный каталог, Вы сможете обращаться к своим функциям как к обычным командам PowerShell.

Интегрированная среда сценариев Windows PowerShell (ISE)

Для того чтобы было удобно писать сценарии, функции и соответственно модули, компания Microsoft разработала специальную графическую программу Integrated Scripting Environment.

Integrated Scripting Environment (ISE) – интегрированная среда сценариев.

Работать в этой программе очень удобно, к тому же она имеет мощный функционал (создание множества вкладок со сценариями, область вывода, встроенный отладчик и другое).

Запустить ее можно следующим образом:

  • В Windows 7 — Пуск->Все программы ->Стандартные ->Windows PowerShell -> Windows PowerShell ISE;
  • В Windows 10 или Windows Server 2016 — Пуск->Все программы -> Каталог Windows PowerShell (в группе W) -> Windows PowerShell ISE.

Примечание! ISE не будет работать на системе Windows Server, установленной в варианте Server Core.

Скриншот интегрированной среды сценариев PowerShell (ISE) в Windows Server 2016

На этом у меня все, надеюсь, материал был Вам полезен! Удачи!

This article covers the differences between the PowerShell versions on different Windows versions. In a new section below, we discuss the differences of Windows PowerShell and PowerShell Core 6. In this article «Windows PowerShell» refers to the PowerShell versions that run on Windows until version 5.1. PowerShell Core or PowerShell 6 refers to the new cross-platform edition of PowerShell.

Contents

  1. Backward compatibility
  2. Check PowerShell version
  3. Switch to PowerShell 2.0
  4. PowerShell 32-bit vs. 64-bit
  5. PowerShell and Windows versions
  6. PowerShell Core, PowerShell 7 supported operating systems
  7. FAQ: Windows PowerShell vs. PowerShell Core
  8. Download Windows PowerShell
  9. Download PowerShell 7
  10. New features in PowerShell 7, PowerShell 7.1 and 7.2
  • Author
  • Recent Posts

Michael Pietroforte is the founder and editor in chief of 4sysops. He has more than 35 years of experience in IT management and system administration.

Please edit this document if you spot an error or if you want to add information.

Backward compatibility

Windows PowerShell is backward compatible with previous versions of Windows PowerShell. Thus, it makes sense to update all machines in your network to the latest Windows PowerShell version. If you use features in a script of a newer PowerShell version on an outdated system, your script will fail. You can easily deploy PowerShell with Group Policy. Note that PowerShell 7 is not fully backward compatible with Windows PowerShell. For more information read PowerShell v5 vs. PowerShell v7—Which to use and when

The Windows PowerShell Compatibility Pack is already available in the PowerShell Gallery. It allows you to import existing modules in PowerShell 6.x and use them like if you are in a PowerShell for Windows console. However, you must be aware that this works fine with a lot of modules but not with all of them. It’s up to you to try which modules can be used with this method or not.

To download and install the module on a computer

Install-Module -Name WindowsCompatibility -Repository PSGallery

After that, you just have to import the WindowsCompatibility module once per session and use the Import-WinModule cmdlet for every non-compatible module you want to run on PowerShell 6.x

PS C:> Import-Module -Name WindowsCompatibility
PS C:> Import-WinModule -Name MyModuleWhichIsNotCompatible
PS C:>

Check PowerShell version

If you want to know what PowerShell version you are using, you can run the $PSVersionTable command.

PS C:> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.15063.674
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.674
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


PS C:>

This also works with PowerShell Core on different operating systems.

PowerShell Core on macOS runs on Darwin

PowerShell Core on macOS runs on Darwin

Switch to PowerShell 2.0

PowerShell 2.0 is integrated in all Windows versions since Windows 7 and Windows Server 2008 R2. If you want to ensure that a PowerShell script also works properly on a system with PowerShell 2.0, you can switch to a PowerShell 2.0 prompt on every Windows version after Windows 7 with PowerShell.exe -Version 2. However, this will only work if you installed .NET Framework 2.0 / 3.5.

PowerShell 32-bit vs. 64-bit

On a Windows 64-bit edition, you will find a 32-bit and a 64-bit version of PowerShell for backward compatibility purposes. If you type “PowerShell” on a Windows Start Screen, you will see “x86” behind the 32-bit versions of PowerShell and PowerShell ISE.

PowerShell (x86)

By and large, the 64-bit and 32-bit PowerShell versions are compatible, and you shouldn’t notice much of a difference. Problems can arise if binaries are involved. For instance, if you want to extend PowerShell with snap-ins (compiled cmdlets), you have to ensure that you download the correct version. You can also run into problems if you want to instantiate an object of a 32-bit application (Microsoft Office, for example) with the 64-bit version of PowerShell.

You can check whether you are in 32-bit or 64-bit shell with [Environment]::Is64BitProcess. If you are running PowerShell 64-bit, you will receive True as output; otherwise, you’ll receive False.

PowerShell Process 32-bit or 64-bit

PowerShell and Windows versions

The following table gives you an overview of the Windows PowerShell versions and how they correlate to the different Windows versions. The Default Windows Versions column tells you the Windows PowerShell version that was delivered with the corresponding Windows version. The links in the Available Windows Versions column allow you to download the Windows PowerShell version for the corresponding Windows version. Note that Windows PowerShell is part of the Windows Management Framework which also includes Windows PowerShell Web Services, Windows Remote Management (WinRM), Windows Management Instrumentation (WMI), and the Server Manager WMI provider.

PowerShell Version Release Date Default Windows Versions Available Windows Versions
PowerShell 1.0 November 2006 Windows Server 2008 (*) Windows XP SP2
Windows XP SP3
Windows Server 2003 SP1
Windows Server 2003 SP2
Windows Server 2003 R2
Windows Vista
Windows Vista SP2
PowerShell 2.0 October 2009 Windows 7
Windows Server 2008 R2 (**)
Windows XP SP3
Windows Server 2003 SP2
Windows Vista SP1
Windows Vista SP2
Windows Server 2008 SP1
Windows Server 2008 SP2
PowerShell 3.0 September 2012 Windows 8
Windows Server 2012
Windows 7 SP1
Windows Server 2008 SP2
Windows Server 2008 R2 SP1
PowerShell 4.0 October 2013 Windows 8.1
Windows Server 2012 R2
Windows 7 SP1
Windows Server 2008 R2 SP1
Windows Server 2012
PowerShell 5.0 February 2016 Windows 10 Windows 7 SP1
Windows 8.1
Windows Server 2012
Windows Server 2012 R2
PowerShell 5.1 January 2017 Windows 10 Anniversary Update
Windows Server 2016
Windows 7 SP1
Windows 8.1
Windows 10
Windows 11
Windows Server 2008 R2 SP1
Windows Server 2012
Windows Server 2012 R2
Windows Server 2019
Windows Server 2022
PowerShell Core 6 January 2018 N/A Windows 7 SP1
Windows 8.1
Windows Server 2008 R2 SP1
Windows Server 2012
Windows Server 2012 R2
PowerShell 7 March 2020 N/A Windows 7 SP1
Windows 8.1
Windows 10
Windows 11
Windows Server 2008 R2 SP1
Windows Server 2012
Windows Server 2012 R2
Windows Server 2019
Windows Server 2022

* Has to be installed through Server Manager
** Also integrated in all later Windows versions

PowerShell Core is the successor of Windows PowerShell 5.1 and runs on Windows, Linux and macOS. The table below lists all supported operating systems and the FAQ at the end of this article answers important questions about the difference between Windows PowerShell and PowerShell Core.

PowerShell Core, PowerShell 7 supported operating systems

OS Windows PowerShell 5.1 PowerShell Core 6.0 PowerShell Core 6.1 PowerShell 7
Windows Windows 7 SP1

Windows 8.1

Windows 10

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2019

Windows Server 2022

Windows Server 2016

Windows 7 SP1

Windows 8.1

Windows 10

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2016

Windows 7 SP1

Windows 8.1

Windows 10 1607+

Windows 11

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2016

Windows Server 2019

Windows Server 2022

Windows 7 SP1

Windows 8.1

Windows 10

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2016

Windows Server 2019

Windows Server 2022

macOS 10.12+ 10.12+ 10.13+
Red Hat Enterprise Linux 7 7 7
CentOS 7 7 7
Oracle Linux 7
Fedora 25, 26 27, 28 29+
Debian 8.7+, 9 8.7+, 9 9+
Ubuntu 14.04, 16.04, 17.04 18, 17 18.10 16.04+
openSUSE 42.2+ 42.2+ 15+
Arch Linux N/A N/A N/A
Kali N/A N/A N/A
Raspbian N/A (ARM32) N/A
Alpine (experimental Docker image coming soon) 3.8+

FAQ: Windows PowerShell vs. PowerShell Core

Does Windows PowerShell have a future?

No, the future belongs to PowerShell Core. As things stand now, Microsoft will only provide bug fixes and security updates for Windows PowerShell. Only PowerShell Core will receive feature updates.

Should I still work with Windows PowerShell or switch to PowerShell 7 now?

This depends on your environment. If all of your systems have PowerShell 7  installed, you might consider moving now. However, PowerShell 7 still has compatibility issues with some modules. Thus, you should have to make sure first that all required modules are available. For more information read this article:

PowerShell v5 vs. PowerShell v7—Which to use and when

Can I run Windows PowerShell and PowerShell 7 on the same Windows computer?

Yes

Can I use PowerShell ISE with PowerShell Core?

No, use Visual Studio Code instead for PowerShell Core.

Will all of my old Windows PowerShell scripts work on PowerShell Core, that is, is PowerShell 7 backward compatible with Windows PowerShell?

Previous PowerShell updates were fully backward compatible. This only applies partly to PowerShell 7. Because PowerShell 7 is a cross-platform edition of PowerShell, Microsoft made a few compromises. This means you have to test each and every Windows PowerShell script to make sure it also works on PowerShell 7.

Will all scripts I write for PowerShell 7 run on all supported platforms?

Basic scripts will run on all platforms. However, considering the huge differences between the supported platforms, you have to test each script on all platforms it is supposed to run on.

Do all modules for Windows PowerShell run on PowerShell 7?

No, many complex modules have to be adapted for PowerShell 7. In some cases, different module versions exist for both PowerShell editions.

Why can’t I launch PowerShell 7 with powershell.exe on a Windows computer?

This is because PowerShell Core and Windows PowerShell have to coexist on Windows computers. You can start PowerShell Core with the pwsh command.

I can’t find the official documentation for PowerShell 7. Where is it?

Microsoft has merged the Windows PowerShell documentation with the PowerShell 7 documentation.
You can find it here.

I have an unanswered question about the differences between PowerShell 7 and Windows PowerShell. Where can I ask it?

Ask in the PowerShell forum.

Should I extend this FAQ by editing this wiki doc?

Definitely, yes!

Download Windows PowerShell

Windows PowerShell is part of the Windows Management Framework. Below all the download links of the different Windows PowerShell versions. To test your script on PowerShell 2.0, please the corresponding section above.

PowerShell 3.0 — Windows Management Framework 3.0

PowerShell 4.0 — (Windows Management Framework 4.0

PowerShell 5.0 — Windows Management Framework 5.0

PowerShell 5.1 — Windows Management Framework 5.1

Download PowerShell 7

You can download PowerShell for every operating system here.

New features in PowerShell 7, PowerShell 7.1 and 7.2

Please read the articles below for more information about the new features in PowerShell 7, PowerShell 7.1 and PowerShell 7.2

Top 10 new features of PowerShell 7

PowerShell v5 vs. PowerShell v7—Which to use and when

How to install PowerShell 7 on Windows and Linux

New features in PowerShell 7.1

How to install and upgrade to PowerShell 7.1

PowerShell 7.2: New features in the Preview

PowerShell

Screenshot of a PowerShell 7 session in Windows Terminal

Paradigm Imperative, pipeline, object-oriented, functional and reflective
Designed by Jeffrey Snover, Bruce Payette, James Truher (et al.)
Developer Microsoft
First appeared November 14, 2006; 16 years ago
Stable release

7.3.7
/ September 18, 2023; 21 days ago[1]

Preview release

v7.4.0-preview.6
/ September 28, 2023; 11 days ago[2]

Typing discipline Strong, safe, implicit and dynamic
Implementation language C#
Platform PowerShell: .NET
Windows PowerShell: .NET Framework
OS
  • Windows 7 and later
  • Windows Server 2008 R2 and later
  • macOS 10.12 and later
  • Ubuntu 14.04, 16.04, 18.04, 20.04 and 22.04
  • Debian 8.7+, 9, 10 and 11
  • CentOS 7 and 8
  • Red Hat Enterprise Linux 7 and 8
  • openSUSE 42.2, 42.3, 15.0, 15.1, 15.2
  • Fedora 28, 29, 30
License MIT License[3] (but the Windows component remains proprietary)
Filename extensions
  • .ps1 (Script)
  • .ps1xml (XML Document)
  • .psc1 (Console File)
  • .psd1 (Data File)
  • .psm1 (Script Module)
  • .pssc (Session Configuration File)
  • .psrc (Role Capability File)
  • .cdxml (Cmdlet Definition XML Document)
Website microsoft.com/powershell
Influenced by
Python, Ksh, Perl, C#, CL, DCL, SQL, Tcl, Tk,[4] Chef, Puppet

PowerShell is a task automation and configuration management program 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 August 18, 2016, with the introduction of PowerShell Core.[5] The former is built on the .NET Framework, the latter on .NET (previously .NET Core).

Since Windows 10 build 14971, PowerShell replaced Command Prompt and became the default command shell for File Explorer.[6][7]

In PowerShell, administrative tasks are generally performed via cmdlets (pronounced command-lets), which are specialized .NET classes implementing a particular operation. These work by accessing data in different data stores, like the file system or Windows Registry, which are made available to PowerShell via providers. Third-party developers can add cmdlets and providers to PowerShell.[8][9] Cmdlets may be used by scripts, which may in turn be packaged into modules. Cmdlets work in tandem with the .NET API.

PowerShell’s support for .NET Remoting, WS-Management, CIM, and SSH enables administrators to perform administrative tasks on both local and remote Windows systems. 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.[8][10] Other Microsoft applications including Microsoft SQL Server 2008 also expose their management interface via PowerShell cmdlets.[11]

PowerShell includes its own extensive, console-based help (similar to man pages in Unix shells) 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[edit]

The command-line interpreter (CLI) has been an inseparable part of most Microsoft operating systems. MS-DOS and Xenix relied almost exclusively on CLI. (MS-DOS 5 came with a complementary graphical DOS Shell.) The Windows 9x family came bundled with COMMAND.COM, the command-line environment of MS-DOS. The Windows NT and Windows CE families, however, came with a new cmd.exe that bore strong similarities to COMMAND.COM. Both environments support a few basic internal commands and a primitive scripting language (batch files), which can be used to automate various tasks. However, they cannot automate all facets of Windows graphical user interface (GUI) because command-line equivalents of operations are limited and the scripting language is elementary.

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 (COM). 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 (such as netsh and WMIC) with their own command sets but they were not interoperable. Windows Server 2003 further attempted to improve the command line experience but scripting support was still unsatisfactory.[12]

Kermit[edit]

By the late 1990s, Intel had come to Microsoft asking for help in making Windows, which ran on Intel CPUs, a more appropriate platform to support the development of future Intel CPUs. At the time, Intel CPU development was accomplished on Sun Microsystems computers which ran Solaris (a Unix variant) on RISC-architecture CPUs. The ability to run Intel’s many KornShell automation scripts on Windows was identified as a key capability. Internally, Microsoft began an effort to create a Windows port of Korn Shell, which was code-named Kermit.[13] Intel ultimately pivoted to a Linux-based development platform that could run on Intel CPUs, rendering the Kermit project redundant. However, with a fully funded team, Microsoft program manager Jeffrey Snover realized there was an opportunity to create a more general-purpose solution to Microsoft’s problem of administrative automation.

Monad[edit]

By 2002, Microsoft had started to develop a new approach to command-line management, including a CLI called Monad (also known as Microsoft Shell or MSH). The ideas behind it were published in August 2002 in a white paper called the «Monad Manifesto» by its chief architect, Jeffrey Snover.[14] In a 2017 interview, Snover explains the genesis of PowerShell, saying that he had been trying to make Unix tools available on Windows, which didn’t work due to «core architectural difference[s] between Windows and Linux». Specifically, he noted that Linux considers everything an ASCII text file, whereas Windows considers everything an «API that returns structured data». They were fundamentally incompatible, which led him to take a different approach.[15]

Monad was to be a new extensible CLI with a fresh design capable of automating a range of core administrative tasks. Microsoft first demonstrated Monad publicly at the Professional Development Conference in Los Angeles in October 2003. A few months later, they opened up private beta, which eventually led to a public beta. Microsoft published the first Monad public beta release on June 17, 2005, and the Beta 2 on September 11, 2005, and Beta 3 on January 10, 2006.

PowerShell[edit]

On April 25, 2006, not long after the initial Monad announcement, Microsoft announced that Monad had been renamed Windows PowerShell, positioning it as a significant part of its management technology offerings.[16] Release Candidate (RC) 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, rather than a mere add-on.

Release Candidate 2 of PowerShell version 1 was released on September 26, 2006, with final release to the web on November 14, 2006. PowerShell for earlier versions of Windows was released on January 30, 2007.[17] PowerShell v2.0 development began before PowerShell v1.0 shipped. During the development, Microsoft shipped three community technology previews (CTP). Microsoft made these releases available to the public. The last CTP release of Windows PowerShell v2.0 was made available in December 2008.

PowerShell for Linux 7.3.1 on Ubuntu 22.10

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.[18] In an October 2009 issue of TechNet Magazine, Microsoft called proficiency with PowerShell «the single most important skill a Windows administrator will need in the coming years».[19]

Windows 10 shipped a testing framework for PowerShell.[20]

On August 18, 2016, Microsoft announced[21] that they had made PowerShell open-source and cross-platform with support for Windows, macOS, CentOS and Ubuntu.[5] The source code was published on GitHub.[22] 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.[23] Starting with version 5.1, PowerShell Core is bundled with Windows Server 2016 Nano Server.[24][25]

Design[edit]

A key design tactic for PowerShell was to leverage the large number of APIs that already existed in Windows, Windows Management Instrumentation, .NET Framework, and other software. PowerShell cmdlets «wrap around» existing functionality. The intent with this tactic is to provide an administrator-friendly, more-consistent interface between administrators and a wide range of underlying functionality. With PowerShell, an administrator doesn’t need to know .NET, WMI, or low-level API coding, and can instead focus on using the cmdlets exposed by PowerShell. In this regard, PowerShell creates little new functionality, instead focusing on making existing functionality more accessible to a particular audience.[26]

Grammar[edit]

PowerShell’s developers based the core grammar of the tool on that of the POSIX 1003.2 KornShell.[27]

However, PowerShell’s language was also influenced by PHP, Perl, and many other existing languages.[28]

Named Commands[edit]

Windows PowerShell can execute four kinds of named commands:[29]

  • cmdlets (.NET Framework 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 launches it in a separate process; if it is a cmdlet, it executes in the PowerShell process. PowerShell provides an interactive command-line interface, where 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.[30]

Extended Type System[edit]

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.[31]

Cmdlets[edit]

Cmdlets are specialized commands in the PowerShell environment that implement specific functions. These are the native commands in the PowerShell stack. Cmdlets follow a VerbNoun naming pattern, such as Get-ChildItem, which makes it self-documenting code.[32] 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.[32]

Cmdlets are specialized .NET classes, which the PowerShell runtime instantiates and invokes at execution time. Cmdlets derive either from Cmdlet or from PSCmdlet, the latter being used when the cmdlet needs to interact with the PowerShell runtime.[32] 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.[33] 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.[34][35]

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[36] 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.[37]

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.[38] 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 a database), they can add specific providers as well.[citation needed]

The number of cmdlets included in the base PowerShell install has generally increased with each version:

Version Cmdlets
Windows PowerShell 1.0 129[39]
Windows PowerShell 2.0 632[40]
Windows PowerShell 3.0 about 1,000[41]
Windows PowerShell 4.0 ?
Windows PowerShell 5.0 about 1,300[42]
Windows PowerShell 5.1 1586[citation needed]
PowerShell Core 6.0 ?
PowerShell Core 6.1 ?
PowerShell Core 6.2 ?
PowerShell 7.0 1507[citation needed]
PowerShell 7.1 ?
PowerShell 7.2 ?

Cmdlets can be added into the shell through snap-ins (deprecated in v2) and modules; users are not limited to the cmdlets included in the base PowerShell installation.

Pipeline[edit]

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 (e.g., to sort the objects by handle count), and then finally to the Select-Object cmdlet to select just the first ten processes based on handle count.[citation needed]

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. Additionally, 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.[43] An object can also encapsulate certain functions that work on the contained data, which become available to the recipient command for use.[44][45] 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.[46][47]

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 backward 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.[48][49][50]

Scripting[edit]

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,[51] 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 (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.[52] 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.[53][54]

Using the function keyword, PowerShell provides for the creation of functions. A simple function has the following general look:[55]

function name ([Type]$Param1, [Type]$Param2) {
  # Instructions
}

However, PowerShell allows for advanced functions that support named parameters, positional parameters, switch parameters and dynamic parameters.[55]

function Verb-Noun {
  param (
    # Definition of static parameters
  )
  dynamicparam {
    # Definition of dynamic parameters
  }
  begin {
    # Set of instruction to run at the start of the pipeline
  }
  process {
    # Main instruction sets, ran for each item in the pipeline
  }
  end {
    # Set of instruction to run at the end of the pipeline
  }
}

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

name value1 value2
Verb-Noun -Param1 value1 -Param2 value2

PowerShell allows any static .NET methods to be called by providing their namespaces enclosed in brackets ([]), and then using a pair of colons (::) to indicate the static method.[56] For example:

[Console]::WriteLine("PowerShell")

There are dozens of ways to create objects in PowerShell. Once created, one can access the properties and instance methods of an object using the . notation.[56]

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.[57]

The following list of special characters is supported by PowerShell:[58]

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). 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.[59]

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 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.[60] 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.[61]

The PowerShell scripting language supports binary prefix notation similar to the scientific notation supported by many programming languages in the C-family.[62]

Hosting[edit]

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 (one instantiation of the PowerShell runtime), which runs in the application’s process and is exposed as a Runspace object.[8] 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.[citation needed]

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.[8] 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.[8] 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.[citation needed]

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 (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.[citation needed]

Desired State Configuration[edit]

DSC allows for declaratively specifying how a software environment should be configured.[63]

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 (LCM) periodically polls the system using the control flow described by resources (imperative pieces of DSC) to make sure that the state of a configuration is maintained.

Versions[edit]

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

Windows PowerShell 1.0[edit]

Windows PowerShell 1.0 session using the Windows Console

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

Windows PowerShell 2.0[edit]

Windows PowerShell ISE v2.0 on Windows 7, an integrated development environment for PowerShell scripts

PowerShell 2.0 is integrated with Windows 7 and Windows Server 2008 R2[65] and is released for Windows XP with Service Pack 3, Windows Server 2003 with Service Pack 2, and Windows Vista with Service Pack 1.[66][67]

PowerShell v2 includes changes to the scripting language and hosting API, in addition to including more than 240 new cmdlets.[68][69]

New features of PowerShell 2.0 include:[70][71][72]

  • PowerShell remoting: Using WS-Management, PowerShell 2.0 allows scripts and cmdlets to be invoked on a remote machine or a large set of remote machines.
  • Background jobs: Also called a PSJob, it allows a command sequence (script) or pipeline to be invoked asynchronously. Jobs can be run on the local machine or on multiple remote machines. An interactive cmdlet in a PSJob blocks the execution of the job until user input is provided.
  • Transactions: Enable cmdlet and developers can perform transactional operations. PowerShell 2.0 includes transaction cmdlets for starting, committing, and rolling back a PSTransaction as well as features to manage and direct the transaction to the participating cmdlet and provider operations. The PowerShell Registry provider supports transactions.
  • Advanced functions: These are cmdlets written using the PowerShell scripting language. Initially called «script cmdlets», this feature was later renamed «advanced functions».[73]
  • SteppablePipelines: This allows the user to control when the BeginProcessing(), ProcessRecord() and EndProcessing() functions of a cmdlet are called.
  • Modules: This allows script developers and administrators to organize and partition PowerShell scripts in self-contained, reusable units. Code from a module executes in its own self-contained context and does not affect the state outside the module. Modules can define a restricted runspace environment by using a script. They have a persistent state as well as public and private members.
  • Data language: A domain-specific subset of the PowerShell scripting language that allows data definitions to be decoupled from the scripts and allows localized string resources to be imported into the script at runtime (Script Internationalization).
  • Script debugging: It allows breakpoints to be set in a PowerShell script or function. Breakpoints can be set on lines, line & columns, commands and read or write access of variables. It includes a set of cmdlets to control the breakpoints via script.
  • Eventing: This feature allows listening, forwarding, and acting on management and system events. Eventing allows PowerShell hosts to be notified about state changes to their managed entities. It also enables PowerShell scripts to subscribe to ObjectEvents, PSEvents, and WmiEvents and process them synchronously and asynchronously.
  • Windows PowerShell Integrated Scripting Environment (ISE): PowerShell 2.0 includes a GUI-based PowerShell host that provides integrated debugger, syntax highlighting, tab completion and up to 8 PowerShell Unicode-enabled consoles (Runspaces) in a tabbed UI, as well as the ability to run only the selected parts in a script.
  • Network file transfer: Native support for prioritized, throttled, and asynchronous transfer of files between machines using the Background Intelligent Transfer Service (BITS).[74]
  • New cmdlets: Including Out-GridView, which displays tabular data in the WPF GridView object, on systems that allow it, and if ISE is installed and enabled.
  • New operators: -Split, -Join, and Splatting (@) operators.
  • Exception handling with Try-Catch-Finally: Unlike other .NET languages, this allows multiple exception types for a single catch block.
  • Nestable Here-Strings: PowerShell Here-Strings have been improved and can now nest.[75]
  • Block comments: PowerShell 2.0 supports block comments using <# and #> as delimiters.[76]
  • New APIs: The new APIs range from handing more control over the PowerShell parser and runtime to the host, to creating and managing collection of Runspaces (RunspacePools) as well as the ability to create Restricted Runspaces which only allow a configured subset of PowerShell to be invoked. The new APIs also support participation in a transaction managed by PowerShell

Windows PowerShell 3.0[edit]

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.[77][78]

PowerShell 3.0 is part of a larger package, Windows Management Framework 3.0 (WMF3), which also contains the WinRM service to support remoting.[78] Microsoft made several Community Technology Preview releases of WMF3. An early community technology preview 2 (CTP 2) version of Windows Management Framework 3.0 was released on December 2, 2011.[79] Windows Management Framework 3.0 was released for general availability in December 2012[80] and is included with Windows 8 and Windows Server 2012 by default.[81]

New features in PowerShell 3.0 include:[78][82]: 33–34 

  • Scheduled jobs: Jobs can be scheduled to run on a preset time and date using the Windows Task Scheduler infrastructure.
  • Session connectivity: Sessions can be disconnected and reconnected. Remote sessions have become more tolerant of temporary network failures.
  • Improved code writing: Code completion (IntelliSense) and snippets are added. PowerShell ISE allows users to use dialog boxes to fill in parameters for PowerShell cmdlets.
  • Delegation support: Administrative tasks can be delegated to users who do not have permissions for that type of task, without granting them perpetual additional permissions.
  • Help update: Help documentations can be updated via Update-Help command.
  • Automatic module detection: Modules are loaded implicitly whenever a command from that module is invoked. Code completion works for unloaded modules as well.
  • New commands: Dozens of new modules were added, including functionality to manage disks get-WmiObject win32_logicaldisk, volumes, firewalls, network connections, and printers, which had previously been performed via WMI.[further explanation needed]

Windows PowerShell 4.0[edit]

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.[83]

New features in PowerShell 4.0 include:

  • Desired State Configuration:[84][85][86] Declarative language extensions and tools that enable the deployment and management of configuration data for systems using the DMTF management standards and WS-Management Protocol
  • New default execution policy: On Windows Servers, the default execution policy is now RemoteSigned.
  • Save-Help: Help can now be saved for modules that are installed on remote computers.
  • Enhanced debugging: The debugger now supports debugging workflows, remote script execution and preserving debugging sessions across PowerShell session reconnections.
  • -PipelineVariable switch: A new ubiquitous parameter to expose the current pipeline object as a variable for programming purposes
  • Network diagnostics to manage physical and Hyper-V’s virtualized network switches
  • Where and ForEach method syntax provides an alternate method of filtering and iterating over objects.

Windows PowerShell 5.0[edit]

PowerShell 5.0 icon

Windows Management Framework (WMF) 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.[87]

Key features included:

  • The new class keyword that creates classes for object-oriented programming
  • The new enum keyword that creates enums
  • OneGet cmdlets to support the Chocolatey package manager[88]
  • Extending support for switch management to layer 2 network switches.[89]
  • Debugging for PowerShell background jobs and instances of PowerShell hosted in other processes (each of which is called a «runspace»)
  • Desired State Configuration (DSC) Local Configuration Manager (LCM) version 2.0
  • DSC partial configurations
  • DSC Local Configuration Manager meta-configurations
  • Authoring of DSC resources using PowerShell classes

Windows PowerShell 5.1[edit]

It was released along with the Windows 10 Anniversary Update[90] on August 2, 2016, and in Windows Server 2016.[91] 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.[92] 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,[93] and was released on January 19, 2017.[94]

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 the .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.[25] This was the final version of PowerShell made exclusively for Windows.

PowerShell Core 6[edit]

PowerShell Core 6.0 was first announced on August 18, 2016, when Microsoft unveiled PowerShell Core and its decision to make the product cross-platform, independent of Windows, free and open source.[5] It achieved general availability on January 10, 2018, for Windows, macOS and Linux.[95] 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.[96]

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 January 11, 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.[97]

6.1[edit]

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.»[98] Still, no details of these cmdlets can be found in the full version of the change log.[99] Microsoft later professes that this number was insufficient as PowerShell Core failed to replace Windows PowerShell 5.1 and gain traction on Windows.[100] It was, however, popular on Linux.[100]

6.2[edit]

PowerShell Core 6.2 is focused primarily on performance improvements, bug fixes, and smaller cmdlet and language enhancements that improved developer productivity.[101]

PowerShell 7[edit]

PowerShell 7 is the replacement for PowerShell Core 6.x products as well as Windows PowerShell 5.1, which is the last supported Windows PowerShell version.[102][100] The focus in development was to make PowerShell 7 a viable replacement for Windows PowerShell 5.1, i.e. to have near parity with Windows PowerShell in terms of compatibility with modules that ship with Windows.[103]

New features in PowerShell 7 include:[104]

  • The -Parallel switch for the ForEach-Object cmdlet to help handle parallel processing
  • Near parity with Windows PowerShell in terms of compatibility with built-in Windows modules
  • A new error view
  • The Get-Error cmdlet
  • Pipeline chaining operators (&& and ||) that allow conditional execution of the next cmdlet in the pipeline
  • The ?: operator for ternary operation
  • The ?? operator for null coalescing
  • The ??= operator for null coalescing assignment
  • Cross-platform Invoke-DscResource (experimental)
  • Return of the Out-GridView cmdlet
  • Return of the -ShowWindow switch for the Get-Help

PowerShell 7.2[edit]

PowerShell 7.2 is the next long-term support version of PowerShell, after version 7.0. It uses .NET 6.0 and features universal installer packages for Linux. On Windows, updates to PowerShell 7.2 and later come via the Microsoft Update service; this feature has been missing from PowerShell 6.0 through 7.1.[105]

PowerShell 7.3[edit]

This version includes some general Cmdlet updates and fixes, testing for framework dependent package in release pipeline as well as build and packaging improvements.[106]

PowerShell 7.4[edit]

[icon]

This section is empty. You can help by adding to it. (April 2023)

Comparison of cmdlets with similar commands[edit]

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.

Notes

  1. ^ a b ls and man aliases are absent in the Linux version of PowerShell Core.
  2. ^ While the external ping command remains available to PowerShell, Test-Connection’s output is a structured object that can be programmatically inspected.[107]
  3. ^ Clear-Host is implemented as a predefined PowerShell function.
  4. ^ a b Available in Windows NT 4, Windows 98 Resource Kit, Windows 2000 Support Tools
  5. ^ a b Introduced in Windows XP Professional Edition
  6. ^ Also used in UNIX to send a process any signal, the «Terminate» signal is merely the default
  7. ^ curl and wget aliases are absent from PowerShell Core, so as to not interfere with invoking similarly named native commands.

Filename extensions[edit]

Extension Description
.ps1 Script file[109]
.psd1 Module’s manifest file; usually comes with a script module or binary module[110]
.psm1 Script module file[111]
.dll DLL-compliant[a] binary module file[112]
.ps1xml Format and type definitions file[50][113]
.xml XML-compliant[b] serialized data file[114]
.psc1 Console file[115]
.pssc Session configuration file[116]
.psrc Role Capability file[117]
  1. ^ Dynamic-link library (DLL) is not a PowerShell-only format. It is a generic format for storing compiled .NET assembly’s code.
  2. ^ XML is not a PowerShell-only format. It is a popular information interchange format.

Application support[edit]

Application Version Cmdlets Provider Management GUI
Exchange Server 2007 402 Yes Yes
Windows Server 2008 Yes Yes No
Microsoft SQL Server 2008 Yes Yes No
Microsoft SharePoint 2010 Yes Yes No
System Center Configuration Manager 2012 R2 400+ Yes No
System Center Operations Manager 2007 74 Yes No
System Center Virtual Machine Manager 2007 Yes Yes Yes
System Center Data Protection Manager 2007 Yes No No
Windows Compute Cluster Server 2007 Yes Yes No
Microsoft Transporter Suite for Lotus Domino[118] 08.02.0012 47 No No
Microsoft PowerTools for Open XML[119] 1.0 33 No No
IBM WebSphere MQ[120] 6.0.2.2 44 No No
IoT Core Add-ons[121] 74 Un­known Un­known
Quest Management Shell for Active Directory[122] 1.7 95 No No
Special Operations Software Specops Command[123] 1.0 Yes No Yes
VMware vSphere PowerCLI[124] 6.5 R1 500+ Yes Yes
Internet Information Services[125] 7.0 54 Yes No
Windows 7 Troubleshooting Center[126] 6.1 Yes No Yes
Microsoft Deployment Toolkit[127] 2010 Yes Yes Yes
NetApp PowerShell Toolkit[128][129] 4.2 2000+ Yes Yes
JAMS Scheduler – Job Access & Management System[130] 5.0 52 Yes Yes
UIAutomation[131] 0.8 432 No No
Dell Equallogic[132] 3.5 55 No No
LOGINventory[133] 5.8 Yes Yes Yes
SePSX[134] 0.4.1 39 No No

Alternative implementation[edit]

A project named Pash, a pun on the widely known «bash» Unix shell, has been an open-source and cross-platform reimplementation of PowerShell via the Mono framework.[135] 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,[136] and finally ceased in 2016 when PowerShell was officially made open-source and cross-platform.[137]

See also[edit]

  • Common Information Model (computing)
  • Comparison of command shells
  • Comparison of programming languages
  • Web-Based Enterprise Management
  • Windows Script Host
  • Windows Terminal

References[edit]

  1. ^ «v7.3.7 Release of PowerShell». PowerShell/PowerShell repo. Microsoft. Retrieved October 6, 2023 – via GitHub.com.
  2. ^ «v7.4.0-preview.6 Release of PowerShell». PowerShell/PowerShell repo. Microsoft. Retrieved October 6, 2023 – via GitHub.com.
  3. ^ «PowerShell for every system!». June 12, 2017 – via GitHub.com.
  4. ^ Snover, Jeffrey (May 25, 2008). «PowerShell and WPF: WTF». Windows PowerShell Blog. Microsoft.
  5. ^ a b c Bright, Peter (August 18, 2016). «PowerShell is Microsoft’s latest open source release, coming to Linux, OS X». Ars Technica. Condé Nast. Archived from the original on April 9, 2020. Retrieved May 12, 2020.
  6. ^ «Announcing Windows 10 Insider Preview Build 14971 for PC».
  7. ^ «PowerShell is replacing Command Prompt».
  8. ^ a b c d e «powershell». Retrieved March 13, 2023.
  9. ^ Truher, Jim (December 2007). «Extend Windows PowerShell With Custom Commands». MSDN Magazine. Microsoft. Archived from the original on October 6, 2008.
  10. ^ Lowe, Scott (January 4, 2007). «Exchange 2007: Get used to the command line». TechRepublic. CBS Interactive. Archived from the original on November 16, 2018. Retrieved May 12, 2020.
  11. ^ Snover, Jeffrey (November 13, 2007). «SQL Server Support for PowerShell!». Windows PowerShell Blog (blog posting). Microsoft. Archived from the original on November 15, 2007. Retrieved November 13, 2007.
  12. ^ Dragan, Richard V. (April 23, 2003). «Windows Server 2003 Delivers Improvements All Around». PCMag.com. Ziff Davis. A standout feature here is that virtually all admin utilities now work from the command line (and most are available through telnet).
  13. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Don Gannon-Jones. p. 25. ISBN 978-1-9536450-3-6.
  14. ^ Jeffrey P. Snover (August 8, 2002). «Monad Manifesto» (PDF). Windows PowerShell Blog. Microsoft. Retrieved April 2, 2021.
  15. ^ Biggar and Harbaugh (September 14, 2017). «The Man Behind Windows PowerShell». To Be Continuous (Podcast). Heavybit. Retrieved September 14, 2017.
  16. ^ «Windows PowerShell (Monad) Has Arrived». Windows PowerShell Blog. Microsoft. April 25, 2006.
  17. ^ Snover, Jeffrey (November 15, 2006). «Windows PowerShell & Windows Vista». Windows PowerShell Blog (blog posting). Microsoft.
  18. ^ «Windows Management Framework (Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0)». Support. Microsoft. September 30, 2013. Archived from the original on October 13, 2013.
  19. ^ Posey, Brien (October 6, 2009). «10 reasons why you should learn to use PowerShell». TechRepublic. Retrieved April 2, 2021.
  20. ^ «What is Pester and Why Should I Care?». December 14, 2015.
  21. ^ Snover, Jeffrey (August 18, 2016). «PowerShell is open sourced and is available on Linux». Microsoft Azure Blog. Microsoft.
  22. ^ «PowerShell/PowerShell». GitHub. Retrieved August 18, 2016.
  23. ^ Hansen, Kenneth; Calvo, Angel (August 18, 2016). «PowerShell on Linux and Open Source!». Windows PowerShell Blog. Microsoft.
  24. ^ Foley, Mary Jo (August 18, 2016). «Microsoft open sources PowerShell; brings it to Linux and Mac OS X». ZDNet. CBS Interactive.
  25. ^ a b «PowerShell on Nano Server». TechNet. Microsoft. October 20, 2016.
  26. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Don Gannon-Jones. p. 45. ISBN 978-1-9536450-3-6.
  27. ^
    Payette, Bruce (2007). Windows PowerShell in Action. Manning Pubs Co Series. Manning. p. 27. ISBN 9781932394900. Retrieved July 22, 2016. The core PowerShell language is based on the POSIX 1003.2 grammar for the Korn shell.
  28. ^ Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Don Gannon-Jones. p. 109. ISBN 978-1-9536450-3-6.
  29. ^ «about_Command_Precedence». TechNet. Microsoft. May 8, 2014.
  30. ^ Wheeler, Sean (September 7, 2021). «about Parsing — PowerShell». Microsoft Docs. Retrieved December 5, 2021.
  31. ^ «Windows PowerShell Extended Type System». Retrieved November 28, 2007.
  32. ^ a b c «Windows PowerShell Cmdlets». Retrieved November 28, 2007.
  33. ^ «Creating Your First Cmdlet». Retrieved November 28, 2007.
  34. ^ «Get-Verb». TechNet. Microsoft. May 8, 2014.
  35. ^ «Cmdlet Overview». MSDN. Microsoft. May 8, 2014.
  36. ^ «Adding parameters That Process Command Line Input». Retrieved November 28, 2007.
  37. ^ «Adding parameters That Process Pipeline Input». Retrieved November 28, 2007.
  38. ^ «Windows PowerShell Providers». Retrieved October 14, 2010.
  39. ^ Yoshizawa, Tomoaki; Ramos, Durval (September 29, 2012). «PowerShell 1.0 Cmdlets». TechNet Articles. Microsoft.
  40. ^ Yoshizawa, Tomoaki (July 10, 2012). «PowerShell 2.0 Cmdlets». TechNet Articles. Microsoft.
  41. ^ Wilson, Ed (2013). «1: Overview of Windows PowerShell 3.0». Windows Powershell 3.0 Step by Step. Sebastopol, California: Microsoft Press. ISBN 978-0-7356-7000-6. OCLC 829236530. Windows PowerShell 3.0 comes with about 1,000 cmdlets on Windows 8
  42. ^ Wilson, Ed (2015). «1: Overview of Windows PowerShell 5.0». Windows PowerShell Step by Step (Third ed.). Redmond, Washington: Microsoft Press. ISBN 978-1-5093-0043-3. OCLC 927112976. Windows PowerShell 5.0 comes with about 1,300 cmdlets on Windows 10
  43. ^ «Windows PowerShell Owner’s Manual: Piping and the Pipeline in Windows PowerShell». TechNet. Microsoft. Retrieved September 27, 2011.
  44. ^ Jones, Don (2008). «Windows PowerShell – Rethinking the Pipeline». Microsoft TechNet. Microsoft. Retrieved November 28, 2007.
  45. ^ «Windows PowerShell Object Concepts». Archived from the original on August 19, 2007. Retrieved November 28, 2007.
  46. ^ «How PowerShell Formatting and Outputting REALLY works». Retrieved November 28, 2007.
  47. ^ «More – How does PowerShell formatting really work?». Retrieved November 28, 2007.
  48. ^ «about_Pipelines». TechNet. Microsoft. May 8, 2014.
  49. ^ «about_Objects». TechNet. Microsoft. May 8, 2014.
  50. ^ a b «about_Format.ps1xml». TechNet. Microsoft. May 8, 2014.
  51. ^ «Anonymous Functions and Code Blocks in PowerShell». Retrieved January 21, 2012.
  52. ^ «Introduction to Windows PowerShell’s Variables». Retrieved November 28, 2007.
  53. ^ «Byte Conversion». Windows PowerShell Tip of the Week. Retrieved November 15, 2013.
  54. ^ Ravikanth (May 20, 2013). «Converting to size units (KB, MB, GB, TB, and PB) without using PowerShell multipliers». PowerShell Magazine.
  55. ^ a b c «about_Functions». Microsoft TechNet. Microsoft. October 17, 2013. Retrieved November 15, 2013.
  56. ^ a b «Lightweight Testing with Windows PowerShell». Retrieved November 28, 2007.
  57. ^ Angelopoulos, Alex; Karen, Bemowski (December 4, 2007). «PowerShell Got Smart About Smart Quotes». Windows IT Pro. Penton Media. Retrieved November 15, 2013.
  58. ^ «About Special Characters». Powershell / Scripting. Microsoft. June 8, 2017. Retrieved June 20, 2019.
  59. ^ «Trap [Exception] { «In PowerShell» }». Retrieved November 28, 2007.
  60. ^ «Running Windows PowerShell Scripts». Microsoft. Retrieved November 28, 2007.
  61. ^ «about_Signing». Microsoft TechNet. Microsoft. October 17, 2013. Retrieved November 15, 2013.
  62. ^ Lee Holmes (September 2006). Windows PowerShell Quick Reference. O’Reilly Media.
  63. ^ eslesar (May 23, 2023). «Windows PowerShell Desired State Configuration Overview». msdn.microsoft.com.
  64. ^ Chung, Leonard; Snover, Jeffrey; Kumaravel, Arul (November 14, 2006). «It’s a Wrap! Windows PowerShell 1.0 Released!». Windows PowerShell Blog. Microsoft.
  65. ^ «PowerShell will be installed by default on Windows Server 08 R2 (WS08R2) and Windows 7 (W7)!». Windows PowerShell Blog. Microsoft. October 28, 2008. Retrieved September 27, 2011.
  66. ^ «Windows Management Framework is here!». October 27, 2009. Retrieved October 30, 2009.
  67. ^ «Microsoft Support Knowledge Base: Windows Management Framework (Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0)». Support.microsoft.com. September 23, 2011. Retrieved September 27, 2011.
  68. ^ «574 Reasons Why We Are So Proud and Optimistic About W7 and WS08R2». Windows PowerShell Blog. Microsoft. October 29, 2008. Retrieved September 27, 2011.
  69. ^ Snover, Jeffrey (2008). «PowerShell: Creating Manageable Web Services». Archived from the original on October 13, 2008. Retrieved July 19, 2015.
  70. ^ «What’s New in CTP of PowerShell 2.0». Retrieved November 28, 2007.
  71. ^ «Windows PowerShell V2 Community Technology Preview 2 (CTP2) – releaseNotes». Microsoft. Archived from the original on May 6, 2008. Retrieved May 5, 2008.
  72. ^ «Differences between PowerShell 1.0 and PowerShell 2.0». Archived from the original on September 17, 2010. Retrieved June 26, 2010.
  73. ^ Jones, Don (May 2010). «Windows PowerShell: Writing Cmdlets in Script». TechNet Magazine. Microsoft.
  74. ^ «GoGrid Snap-in – Managing Cloud Services with PowerShell». Windows PowerShell Blog. Microsoft. October 14, 2008. Retrieved September 27, 2011.
  75. ^ «Emit-XML». Windows PowerShell Blog. Microsoft. October 17, 2008. Retrieved September 27, 2011.
  76. ^ «Block Comments in V2». Windows PowerShell Blog. Microsoft. June 14, 2008. Retrieved September 27, 2011.
  77. ^ Lee, Thomas (August 13, 2012). «PowerShell Version 3 is RTM!». Under The Stairs. Retrieved August 13, 2012.
  78. ^ a b c «Windows Management Framework 3.0». Download Center. Microsoft. September 4, 2012. Retrieved November 8, 2012.
  79. ^ «Windows Management Framework 3.0 Community Technology Preview (CTP) #2 Available for Download». Windows PowerShell Blog. Microsoft. December 2, 2011.
  80. ^ «Windows Management Framework 3.0». Download Center. Microsoft. December 3, 2012.
  81. ^ Jofre, JuanPablo (December 14, 2016). «Windows PowerShell System Requirements». Microsoft Developer Network. Microsoft. Retrieved April 20, 2017.
  82. ^ Honeycutt, Jerry (2012). Woolley, Valerie (ed.). Introducing Windows 8: An Overview for IT Professionals. Redmond, WA: Microsoft Press. ISBN 978-0-7356-7050-1.
  83. ^ «Windows Management Framework 4.0 is now available». Microsoft. October 24, 2013. Retrieved November 4, 2013.
  84. ^ Levy, Shay (June 25, 2013). «New Features in Windows PowerShell 4.0». PowerShell Magazine. Retrieved June 26, 2013.
  85. ^ «Desired State Configuration in Windows Server 2012 R2 PowerShell». Channel 9. Microsoft. June 3, 2013. Archived from the original on December 26, 2013. Retrieved June 26, 2013.
  86. ^ Hall, Adrian (June 7, 2013). «Thoughts from Microsoft TechEd North America». Blogs: Tips & Tricks. Splunk. Retrieved June 26, 2013.
  87. ^ «Windows Management Framework (WMF) 5.0 RTM packages has been republished». Windows PowerShell Blog. Microsoft. February 24, 2016.
  88. ^ «Q and A». GitHub. Retrieved April 21, 2015.
  89. ^ Snover, Jeffrey (April 3, 2014). «Windows Management Framework V5 Preview». blogs.technet.com. Microsoft. Archived from the original on June 30, 2014. Retrieved April 21, 2015.
  90. ^ says, Jaap Brasser (August 2, 2016). «#PSTip New PowerShell Commands in Windows 10 Anniversary Update».
  91. ^ «What’s New In Windows Server 2016 Standard Edition Part 9 – Management And Automation». September 4, 2016.
  92. ^ «Microsoft.PowerShell.LocalAccounts Module». technet.microsoft.com. June 16, 2016.
  93. ^ «Announcing Windows Management Framework (WMF) 5.1 Preview». July 16, 2016.
  94. ^ «WMF 5.1». Microsoft Download Center.
  95. ^ Aiello, Joey (January 11, 2018). «PowerShell Core 6.0: Generally Available (GA) and Supported!». PowerShell Team Blog. Microsoft. Archived from the original on June 11, 2018. Retrieved June 11, 2018.
  96. ^ Aiello, Joey; Wheeler, Sean (January 10, 2018). «PowerShell Core Support Lifecycle». Microsoft Docs. Microsoft.
  97. ^ Calvo, Angel (January 11, 2018). «Top 10 most exciting reasons to migrate». PowerShell AMA. Microsoft.
  98. ^ Aiello, Joey (September 13, 2018). «Announcing PowerShell Core 6.1». devblogs.microsoft.com. Microsoft. Retrieved June 1, 2019.
  99. ^ «PowerShell/PowerShell». GitHub. Retrieved June 22, 2020.
  100. ^ a b c Lee, Steve (April 5, 2019). «The Next Release of PowerShell – PowerShell 7». Microsoft. Retrieved June 1, 2019.
  101. ^ Lee, Steve (March 28, 2019). «General Availability of PowerShell Core 6.2». devblogs.microsoft.com. Microsoft. Retrieved June 1, 2019.
  102. ^ Mackie, Kurt (May 30, 2019). «Microsoft Releases PowerShell 7 Preview». 1105 Media Inc. Retrieved June 1, 2019.
  103. ^ Lee, Steve (May 30, 2019). «PowerShell 7 Road Map». devblogs.microsoft.com. Microsoft. Retrieved August 12, 2020.
  104. ^ «PowerShell 7 Preview 5 | PowerShell». October 23, 2019. Archived from the original on February 15, 2020. Retrieved March 5, 2020.
  105. ^ «PowerShell 7.2 is the new version of Microsoft’s next-generation shell». itsfoss.net. November 12, 2021.
  106. ^ «Release v7.3.0 Release of PowerShell · PowerShell/PowerShell». GitHub. Archived from the original on November 9, 2022. Retrieved March 7, 2022.
  107. ^ «Test-Connection». PowerShell documentations. Microsoft. August 9, 2015.
  108. ^ «Tar and Curl Come to Windows! — Microsoft Tech Community — 382409». March 22, 2019. Archived from the original on September 11, 2020. Retrieved May 17, 2020.
  109. ^ Wheeler, Sean (June 2, 2020). «About Scripts». Microsoft Docs. Microsoft.
  110. ^ Wheeler, Sean; Smatlak, David; Wilson, Chase (October 16, 2019). «How to write a PowerShell module manifest». Docs. Microsoft.
  111. ^ Wheeler, Sean; Smatlak, David (November 22, 2019). «How to Write a PowerShell Script Module». Microsoft Docs. Microsoft.
  112. ^ Wheeler, Sean (November 13, 2016). «How to Write a PowerShell Binary Module». Microsoft Docs. Microsoft.
  113. ^ Wheeler, Sean; Jofre, Juan Pablo; Vorobev, Sergei; Nikolaev, Kirill; Coulter, David (June 2, 2020). «About Types.ps1xml». Microsoft Docs. Microsoft.
  114. ^ Wheeler, Sean. «Export-Clixml». Microsoft Docs. Microsoft.
  115. ^ Wheeler, Sean; Jofre, Juan Pablo; Vorobev, Sergei; Nikolaev, Kirill; Coulter, David. «Export-Console». Microsoft Docs. Microsoft.
  116. ^ Wheeler, Sean (June 2, 2020). «About Session Configuration Files». Microsoft Docs. Microsoft.
  117. ^ Wheeler, Sean (June 2, 2020). «New-PSRoleCapabilityFile». Microsoft Docs. Microsoft.
  118. ^ «Microsoft Transporter Suite for Lotus Domino». Microsoft. Retrieved March 7, 2008.
  119. ^ «PowerTools for Open XML». Retrieved June 20, 2008.
  120. ^ «MO74: WebSphere MQ – Windows PowerShell Library». Retrieved December 5, 2007.
  121. ^ «IoT Core Add-ons command-line options». Retrieved June 13, 2020.
  122. ^ «PowerShell Commands for Active Directory by Quest Software». Retrieved July 2, 2008.
  123. ^ «PowerShell Remoting through Group Policy». Retrieved December 7, 2007.
  124. ^ «VMware vSphere PowerCLI». Archived from the original on December 30, 2014. Retrieved September 9, 2014.
  125. ^ «Windows PowerShell : IIS7 PowerShell Provider Tech Preview 2». Retrieved July 3, 2008.
  126. ^ «Kudos to the Win7 Diagnostics Team». Retrieved June 15, 2009.
  127. ^ Michael, Niehaus (July 10, 2009). «MDT 2010 New Feature #16: PowerShell support». Retrieved October 27, 2014.
  128. ^ «Kudos to NetApp for Data ONTAP PowerShell ToolKit». Retrieved June 15, 2010.
  129. ^ «PowerShell Toolkit 4.2 Announcement». June 23, 2016. Retrieved September 7, 2016.
  130. ^ «Heterogeneous Job Scheduling With PowerShell». Retrieved September 15, 2010.
  131. ^ «UIAutomation PowerShell Extensions». Archived from the original on August 17, 2016. Retrieved February 16, 2012.
  132. ^ «EqualLogic HIT-ME with PowerShell». Retrieved March 9, 2012.
  133. ^ de:LOGINventory
  134. ^ «Selenium PowerShell eXtensions». Archived from the original on January 19, 2013. Retrieved August 20, 2012.
  135. ^ «Pash». SourceForge. Dice Holdings, Inc. Retrieved September 27, 2011.
  136. ^ «Pash Project». GitHub. Retrieved April 10, 2013.
  137. ^ «Pash is now obsolete · Issue #429 · Pash-Project/Pash». GitHub. Retrieved November 26, 2019.

Further reading[edit]

  • Finke, Douglas (2012). Windows PowerShell for Developers. O’Reilly Media. ISBN 978-1-4493-2270-0.
  • Holmes, Lee (2006). Windows PowerShell Quick Reference. O’Reilly Media. ISBN 0-596-52813-2.
  • Holmes, Lee (2007). Windows PowerShell Cookbook. O’Reilly Media. ISBN 978-0-596-52849-2.
  • Jones, Don; Hicks, Jeffery (2010). Windows PowerShell 2.0: TFM (3rd ed.). Sapien Technologies. ISBN 978-0-9821314-2-8.
  • Jones, Don (2020). Shell of an Idea: The Untold History of PowerShell. Self-published. ISBN 978-1-9536450-3-6.
  • Kopczynski, Tyson; Handley, Pete; Shaw, Marco (2009). Windows PowerShell Unleashed (2nd ed.). Pearson Education. ISBN 978-0-672-32988-3.
  • Kumaravel, Arul; White, Jon; Naixin Li, Michael; Happell, Scott; Xie, Guohui; Vutukuri, Krishna C. (2008). Professional Windows PowerShell Programming: Snapins, Cmdlets, Hosts and Providers. Wrox Press. ISBN 978-0-470-17393-0.
  • Oakley, Andy (2005). Monad (AKA PowerShell). O’Reilly Media. ISBN 0-596-10009-4.
  • Watt, Andrew (2007). Professional Windows PowerShell. Wrox Press. ISBN 978-0-471-94693-9.
  • Wilson, Ed (2013). Windows PowerShell 3.0 Step by Step. Microsoft Press. ISBN 978-0-7356-6339-8.
  • Wilson, Ed (2014). Windows PowerShell Best Practices. Microsoft Press. ISBN 978-0-7356-6649-8.

External links[edit]

Wikiversity has learning resources about PowerShell

  • Official website Edit this at Wikidata
  • PowerShell on GitHub
  • Windows PowerShell Survival Guide on TechNet Wiki

Материал из Национальной библиотеки им. Н. Э. Баумана
Последнее изменение этой страницы: 14:25, 29 декабря 2016.

PowerShell

1451916303 image0021.jpg
Спроектировано Jeffrey Snover, Bruce Payette, James Truher (et al.)
Разработчики Microsoft
Первый   появившийся 14 ноября, 2006 года
Стабильная версия 5.1.14393 / 2 August 2016 года; 6 years ago
Предварительный выпуск 6.0.0 Alpha 10 / 15 September 2016 года; 6 years ago
Платформа .NET Framework, .NET Core
OS Windows XP и боле поздние, OS X, CentOS, Ubuntu
Лицензия Лицензия MIT

Microsoft Windows PowerShell — это оболочка командной строки на основе задач, а также язык сценариев, предназначенный специально для системного администрирования. Созданная на основе .NET Framework, служба Windows PowerShell помогает ИТ-специалистам и опытным пользователям в управлении и автоматизации администрирования операционной системы Windows, а также приложений, работающих под управлением Windows.

Команды Windows PowerShell, которые называются командлетами, позволяют управлять компьютерами из командной строки. Поставщики Windows PowerShell позволяют получить доступ к хранилищам данных, например реестру и хранилищу сертификатов, так же легко, как и к файловой системе. Кроме того, Windows PowerShell включает многофункциональное средство синтаксического анализа выражений и полностью разработанный язык сценариев.

Windows PowerShell содержит следующие функции.

  • Командлеты для выполнения обычных задач системного администрирования, таких как управление реестром, службами, процессами и журналами событий, а также использование инструментария управления Windows (WMI).
  • Язык сценариев на основе задач и поддержка существующих сценариев и программ командной строки.
  • Единый дизайн. Так как командлеты и хранилища системных данных используют обычный синтаксис и соглашения об именовании, можно легко предоставлять общий доступ к данным, а выходные данные одного командлета можно использовать в качестве входных данных в другой командлет без переформатирования или каких-либо операций.
  • Упрощенная навигация операционной системы на основе команд, которая позволяет пользователям перемещаться по реестру и другим хранилищам данных, используя те же техники, которые используются для навигации по файловой системе.
  • Обширные возможности операций с объектами. Объектами можно управлять напрямую или отправлять их в другие инструменты или базы данных.
  • Расширяемый интерфейс. Независимые поставщики программного обеспечения и корпоративные разработчики могут создавать пользовательские инструменты и служебные программы для администрирования программного обеспечения. [1]

Содержание

  • 1 История
  • 2 Назначение
  • 3 Командлеты
  • 4 Версии
    • 4.1 PowerShell 1.0
    • 4.2 PowerShell 2.0
    • 4.3 PowerShell 3.0
    • 4.4 PowerShell 4.0
    • 4.5 PowerShell 5.0
  • 5 Сценарии, функции и модули
  • 6 Источники
  • 7 Ссылки

История

Каждая выпущенная версия MS-DOS и Microsoft Windows для персональных компьютеров содержала утилиту, предоставляющую интерфейс командной строки. Это были COMMAND.COM (в системах, основанных на MS-DOS, включая Windows 9x) и cmd.exe (в системах семейства Windows NT). Это были обычные интерпретаторы командной строки, имевшие лишь несколько базовых команд. Для других задач требовались отдельные консольные приложения, которые вызывались из этих оболочек. Они также имели язык сценариев (пакетные файлы), при помощи которого можно было автоматизировать различные задачи. Однако эти интерпретаторы не годились для полноценной автоматизации — частично потому, что в них отсутствовали эквиваленты многих операций графического интерфейса, а также из-за слабой функциональности языка сценариев, не позволявшего описывать достаточно сложные алгоритмы. В Windows Server 2003 ситуация была улучшена, однако поддержка сценариев всё ещё считалась недостаточной.

Microsoft пыталась решить некоторые из этих недостатков с помощью Windows Script Host, вышедшего в 1998 году в составе Windows 98, и утилиты для работы с ним из командной строки cscript.exe. Он интегрируется с Active Script и позволяет писать сценарии на совместимых языках, таких, как JScript и VBScript, используя API, предоставляемое приложениями через Component Object Model (COM). Однако у этого решения свои недочёты. Windows Script Host не интегрирован с оболочкой, отсутствует встроенная документация. Различные версии Windows также предоставляют командные интерпретаторы специального назначения (такие, как netsh.exe и WMIC) со своими собственными наборами команд. Они не интегрированы с командной оболочкой и не дают возможностей для взаимодействия.

В 2003 Microsoft начала разработку новой оболочки, называемой Monad (также известной как Microsoft Shell или MSH). Monad должен был стать новой расширяемой оболочкой командой строки, со свежим дизайном, который позволял бы автоматизировать весь спектр административных задач. Microsoft опубликовала первую публичную бета-версию Monad 17 июня 2005 года. Вторая и третья бета-версии были выпущены 11 сентября 2005 и 10 января 2006 соответственно. 25 апреля 2006 года было объявлено, что Monad переименован в Windows PowerShell для позиционирования его в качестве значительной части их технологий управления. В это же время была выпущена версия Release Candidate 1 («кандидат на выпуск»). Release Candidate 2 последовал 26 сентября 2006 года. Финальная версия (Release to Web, RTW) была выпущена 14 ноября 2006 года для Windows XP SP2 и Windows 2003. Финальная версия для Windows Vista стала доступна только 30 января 2007 года.

Последний CTP выпуск Windows PowerShell версии 2.0 был выпущен в декабре 2008 года. Финальная версия второй версии PowerShell была выпущена в составе систем Windows 7 и Windows Server 2008 R2 одновременно с их выпуском. Для остальных систем (Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008), вторая версия PowerShell стала доступна в составе комплекта Windows Management Framework 27 октября 2009 года. Кроме Windows PowerShell второй версии, в этот комплект также входят WinRM версии 2.0 и BITS 4.0 (последний доступен только для Windows Vista и Windows 2008; в Windows 7 и Windows Server 2008 R2 он встроен).

Назначение

Windows PowerShell является ключевым инструментом управления, в отличие от Microsoft Management Console (MMC). Возможно, вы знаете, что консоль MMC сама по себе во многих случаях оказывается бесполезной. Для того, чтобы сделать ее полезной, необходимо добавлять оснастки. Оснастки дают специфические возможности управления продуктами и технологиями, например, возможность администрирования активной директории или Exchange Server.

Windows PowerShell действует по такому же принципу. Несмотря на то, что оболочка выполняет множество полезных функций, ее возможности предполагается расширять с помощью всевозможных оснасток и модулей. Windows PowerShell сама по себе не содержит эти оснастки и модули; они устанавливаются параллельно с тем продуктом, функцией или технологией, к которой они относятся. Другими словами, если вы хотите с помощью Windows PowerShell управлять службами Active Directory Domain Services, вам необходимо установить соответствующий модуль. Этот модуль устанавливается вместе с ролью Active Directory® Domain Services. Некоторые модули также могут быть установлены параллельно с удаленным сервером Windows Remote Server Administration Toolkit (RSAT), что делает возможным установить модули, имеющие отношение к серверу, на клиентской операционной системе, например, Windows 7.

Некоторые модули можно загрузить отдельно. Например, на сайте CodePlex Web (www.codeplex.com) можно найти ряд проектов, имеющих отношение к Windows PowerShell со сторонних открытых источников. Многие из этих проектов имеют вид оснастки или модуля. К ним относится, например, популярный проект Windows PowerShell Community Extensions, который можно скачать с www.codeplex.com/powershellcx. Отдельно стоит упомянуть, что некоторые оснастки и модули помимо требований Windows PowerShell могут иметь свои собственные системные требования. Например, модулям может потребоваться конкретная версия Windows или Microsoft .NET Framework. В документации к каждому модулю или оснастке должны быть указаны специфические системные требования, помимо базовых требований оболочки.

Командлеты

Командлеты именуются по правилу Глагол-Существительное, например, Get-ChildItem, благодаря чему их предназначение понятно из названия. Командлеты выводят результаты в виде объектов или их коллекций. Дополнительно командлеты могут получать входные данные в такой же форме и, соответственно, использоваться как получатели в конвейере. Хотя PowerShell позволяет передавать по конвейеру массивы и другие коллекции, командлеты всегда обрабатывают объекты поочередно. Для коллекции объектов обработчик командлета вызывается для каждого объекта в коллекции по очереди.

Экземпляры объектов создаются в PowerShell и запускаются им при вызове. Командлеты наследуются от Cmdlet или от PSCmdlet, причём последний используется тогда, когда командлету необходимо взаимодействовать с исполняемой частью PowerShell (англ. PowerShell runtime). В этих базовых классах оговорены некоторые методы — BeginProcessing(), ProcessRecord() и EndProcessing(), как минимум один из которых реализация командлета должна перезаписать для предоставления своей функциональности. Каждый раз при запуске командлета эти методы вызываются PowerShell по очереди. Сначала вызывается BeginProcessing(), затем, если командлету передаются данные по конвейеру, ProcessRecord() для каждого элемента, и в самом конце — EndProcessing(). Класс, реализующий Cmdlet, должен иметь один атрибут .NET — CmdletAttribute, в котором указываются глагол и существительное, составляющие имя командлета. Популярные глаголы представлены в виде перечисления.[2]

Версии

Первая версия PowerShell 1.0 появилась 14 ноября 2006 года и выпускалась в виде отдельного дистрибутива, который можно было установить на следующие версии операционных систем Windows: Windows XP Service Pack 2, Windows Server 2003 Service Pack 1 и Windows Vista.

В Windows Server 2008 PowerShell 1.0 поставлялся в виде компонента, который также нужно было устанавливать.

Начиная с Windows 7 и Windows Server 2008 R2, PowerShell поставляется как неотъемлемый компонент системы. Ниже представлена таблица соответствия версии PowerShell и версии операционной системы Windows:

PowerShell Windows
PowerShel l2.0 Windows 7, Windows Server 2008 R2
PowerShell 3.0 Windows 8, Windows Server 2012
PowerShell 4.0 Windows 8.1, Windows Server 2012 R2
PowerShell 5.0 Windows 10, Windows Server 2016

С каждой новой версией PowerShell становится все более мощным инструментом администрирования, для сравнения в первой PowerShell было около 130 командлетов, а в PowerShell 5.0 их уже более 600.[3]

PowerShell 1.0

PowerShell 1.0 появилась 14 ноября 2006 года и выпускалась в виде отдельного дистрибутива, который можно было установить на следующие версии операционных систем Windows: Windows XP Service Pack 2, Windows Server 2003 Service Pack 1 и Windows Vista.

PowerShell 2.0

Microsoft выпустила PowerShell 2.0 в составе Windows 7 и Windows Server 2008 R2. Windows PowerShell 2.0 предустановлен в этих системах. Исключением является режим установки Windows Server 2008 R2 в режиме Core, где PowerShell 2.0 можно доустановить вручную. Для более старых платформ он доступен в составе Windows Management Framework. PowerShell 2.0 вносит некоторые изменения в язык сценариев и API для встраивания, в дополнение к новым 240 командлетам.

Неполный список новых возможностей, включённых в PowerShell 2.0:

  • PowerShell Remoting. Используя WS-Management, PowerShell 2.0 позволяет вызывать сценарии и командлеты на удалённых машинах (в том числе и на нескольких одновременно), отслеживать состояние их выполнения и получать результаты в виде объектов (через сериализацию-десериализацию). Также возможно устанавливать интерактивные сессии и сессии с ограниченной функциональностью.
  • Фоновые работы. Возможность вызывать последовательности команд асинхронно. Работы можно запускать на локальной машине или на нескольких удалённых машинах. Работы не могут использовать интерактивные командлеты.
  • Транзакции. Позволяют разработчикам командлетов и поставщиков реализовывать транзакционные операции. PowerShell 2.0 включает командлеты для инициализации, подтверждения и отката транзакций и возможности для управления транзакциями и использования их в командлетах и поставщиках.
  • Advanced Functions. Возможность разрабатывать полноценные командлеты, используя только сам PowerShell.
  • SteppablePipelines. Позволяет пользователю контролировать вызов функций BeginProcessing(), ProcessRecord() и EndProcessing() при вызове командлета.
  • Модули. Позволяют авторам сценариев и администраторам организовывать сценарии PowerShell и помещать их в самодостаточные модули. Код из модуля выполняется в своем собственном, независимом контексте и не влияет на окружение вне модуля. Используя сценарий, модули могут объявлять ограниченное окружение. Модули могут содержать публичные и приватные функции и переменные.
  • Язык данных. Подмножество языка PowerShell, которое позволяет отделять определения данных от исполняемого кода сценариев и даёт возможность импортировать в сценарий локализованные строки в процессе выполнения.
  • Отладка сценариев. Возможность устанавливать точки прерывания (англ. breakpoints) в сценариях или функциях PowerShell. Точки прерывания могут быть установлены на строки, столбцы, команды или операции чтения и/или записи переменных. Присутствуют командлеты для установки и контроля точек прерывания в сценариях.
  • Eventing (событирование). Эта возможность позволяет слушать, перенаправлять, и выполнять действия при возникновении событий управления или системы. Благодаря событированию хосты PowerShell могут быть оповещены о изменениях состояния в управляемых объектах. Также позволяет сценариям подписываться на ObjectEvents, PSEvents и WmiEvents и обрабатывать их синхронно и асинхронно.
  • Windows PowerShell Integrated Scripting Environment (ISE). PowerShell 2.0 включает графическую оболочку для языка, в которую входят встроенный отладчик, подсветка синтаксиса, автозавершение команд. Оболочка позволяет запускать несколько независимых консолей PowerShell с полной поддержкой Юникода в интерфейсе с закладками. Благодаря поддержке удалённого выполнения некоторые консоли могут выполняться и на других компьютерах. Кроме того, ISE позволяет выполнять только выделенные части сценариев, содержит встроенный редактор и позволяет расширять и дополнять свой интерфейс с помощью PowerShell.
  • BITS Transfer — встроенная поддержка передачи файлов по сети с приоритизацией, многопоточностью, возобновлением и асинхронной работой на основе технологии Background Intelligent Transfer Service.
  • Множество новых командлетов, включая, например, Out-GridView, позволяющий вывести результаты конвейера в графическую таблицу (на основе WPF), с возможностями сортировки и мгновенного поиска.
  • Новые операторы -Split, -Join и оператор подстановки (@).
  • Обработка ошибок с Try-Catch-Finally. В отличие от других .NET языков, в PowerShell можно указывать несколько типов исключений для одного блока catch.
  • Блочные комментарии. PowerShell 2.0 поддерживает блочные комментарии (плюс к уже имеющимся построчным #) с использованием <# и #> в качестве ограничителей.
  • Новые API добавили разные возможности, от большего контроля над парсером PowerShell до способности создавать ограниченные сессии (англ. restricted runspace), в которых можно выполнять лишь ограниченный набор инструкций и команд PowerShell.

PowerShell 3.0

PowerShell 3.0 интегрирован с Windows 8 и с Windows Server 2012. Microsoft также сделала PowerShell 3.0, доступное для Windows 7 с пакетом обновления 1 для Windows Server 2008 с пакетом обновления 1, а также для Windows Server 2008 R2 с пакетом обновления 1.

Windows PowerShell 3.0 включает новые функции:

  • Рабочие процессы Windows PowerShell
  • Windows PowerShell Web Access
  • Новые возможности в интегрированной среде скриптов Windows PowerShell
  • Поддержка Microsoft .NET Framework 4.0
  • Поддержка среды предустановки Windows
  • Отключенные сеансы
  • Надежная связь для сеансов
  • Система обновляемой справки
  • Усовершенствованная справка в Интернете
  • Интеграция с CIM
  • Файлы конфигурации сеанса
  • Интеграция запланированных заданий и планировщика задач
  • Усовершенствования в языке Windows PowerShell
  • Новые основные командлеты
  • Усовершенствования в существующих основных командлетах и поставщиках
  • Удаленный импорт и обнаружение модулей
  • Усовершенствованное завершение нажатием клавиши TAB
  • Автоматическая загрузка модулей
  • Улучшение работы с модулями
  • Упрощенное обнаружение команд
  • Улучшенная поддержка ведения журнала, диагностики и групповой политики
  • Усовершенствования, связанные с форматированием и выходными данными
  • Усовершенствованное взаимодействие с узлом консоли
  • Новые API-интерфейсы командлетов и размещения
  • Повышение производительности
  • Поддержка запуска от имени и общего узла
  • Улучшения в обработке специальных символов

PowerShell 4.0

PowerShell 4.0 интегрируется с ОС Windows 8.1 и Windows Server 2012 R2. Microsoft также сделала PowerShell 4.0 для Windows 7 SP1, Windows Server 2008 R2 SP1 и Windows Server 2012.

Некоторые новые возможности в PowerShell 4.0:

  • Новые возможности в Windows PowerShell
  • Новые возможности в интегрированной среде скриптов Windows PowerShell
  • Новые возможности в рабочих процессах Windows PowerShell
  • Новые возможности в веб-службах Windows PowerShell
  • Новые возможности в Windows PowerShell Web Access
  • Исправления важных ошибок в Windows PowerShell 4.0

PowerShell 5.0

Новые функции в Windows PowerShell 5.0:

  • Новые возможности в Windows PowerShell
  • Новые возможности для настройки требуемого состояния Windows PowerShell
  • Новые возможности в интегрированной среде скриптов Windows PowerShell
  • Новые возможности в веб-службах Windows PowerShell
  • Исправления важных ошибок в Windows PowerShell 5.0[4]

Сценарии, функции и модули

Если Вы написали некий алгоритм, скорей всего Вы захотите сохранить его, для того чтобы в дальнейшем им пользоваться. В Windows PowerShell для этих целей существует механизм использования сценариев.
Суть данного механизма следующая, Вы пишите нужный Вам набор команд и сохраняете его в качестве сценария — это простой текстовый файл с расширением .PS1.
Затем, для того чтобы выполнить этот сценарий, Вы просто запускаете его в оболочке PowerShell. При этом Вам необходимо либо указать полный путь к файлу сценария, либо перейти в каталог со сценарием и вызвать его по имени.

По умолчанию выполнение сценариев в Windows запрещено. Для того чтобы посмотреть политику выполнения сценариев выполните командлет Get-ExecutionPolicy. В результате он вернет действующую политику, например:

  • Restricted – блокируется выполнение любых сценариев (значение по умолчанию);
  • AllSigned – разрешено выполнение сценариев, которые имеют цифровую подпись;
  • RemoteSigned – разрешено выполнение локальных сценариев, все скачанные сценарии должны иметь цифровую подпись;
  • Unrestricted — разрешено выполнение любых сценариев

Для разрешения выполнения сценариев необходимо использовать командлет Set-ExecutionPolicy с одним из вышеперечисленных параметров.
В сценарии можно передавать параметры, делать их обязательными или задавать значение по умолчанию.
В Windows PowerShell предусмотрен механизм создания собственных функций, которые также как и встроенные командлеты можно будет использовать в оболочке PowerShell.
Для этого необходимо указать ключевое слово Function и затем в фигурных скобках {} написать алгоритм работы этой функции, т.е. набор команд (например, какая-нибудь часто используемая процедура: создать пользователя с определенными правами, очистить определенные каталоги и так далее). Потом необходимо сохранить все это в сценарий, но только уже с расширением .psm1, так как этот файл будет являться уже модулем.
Это еще не все, этот файл необходимо поместить в каталог, в котором PowerShell ищет модули. Таких каталогов несколько (специальный каталог в профиле пользователя, каталог, где установлен PowerShell), их можно посмотреть в переменных окружения PowerShell.

Источники

  1. Microsoft [Электронный ресурс]:
    Работа со сценариями в Windows PowerShell / Дата обращения: 17.12.2016. — Режим доступа: https://technet.microsoft.com/ru-ru/library/bb978526.aspx
  2. Википедия [Электронный ресурс]: Windows PowerShell / Дата обращения: 17.12.2016. — Режим доступа: https://ru.wikipedia.org/wiki/Windows_PowerShell
  3. Info-Comp [Электронный ресурс]:
    Основы Windows PowerShell / Дата обращения: 17.12.2016. — Режим доступа: http://info-comp.ru/sisadminst/546-windows-powershell-basics.html#PowerShellVersions
  4. Microsoft [Электронный ресурс]:
    Новые возможности Windows PowerShell / Дата обращения: 17.12.2016. — Режим доступа: https://msdn.microsoft.com/ru-ru/powershell/scripting/whats-new/what-s-new-in-windows-powershell-50

Ссылки

  • Франк Кох. Windows PowerShell(Введение в технологии языка сценариев для пользователей без базовых знаний). — С. 44. — http://window.edu.ru/resource/459/61459/files/Windows_Powershell%20-%20RU.pdf
  • Techdays [Электронный ресурс]: Доклад о возможностях PowerShell и основах написания сценариев / Дата обращения: 17.12.2016. — Режим доступа: https://www.techdays.ru/videos/1187.html
  • habrahabr [Электронный ресурс]: Jump Start в PowerShell (часть I) / Дата обращения: 17.12.2016. — Режим доступа: https://habrahabr.ru/post/242425/
  • habrahabr [Электронный ресурс]: Jump Start в PowerShell (часть II) / Дата обращения: 17.12.2016. — Режим доступа: https://habrahabr.ru/post/242445/
  • computerinfo [Электронный ресурс]: Что такое PowerShell? / Дата обращения: 17.12.2016. — Режим доступа: http://computerinfo.ru/chto-takoe-powershell/

В данной статье мы рассмотрим такую технологию от компании Microsoft как Windows PowerShell, мы поговорим о том, что такое PowerShell, что такое командлеты и конвейер, как писать сценарии и модули, а также затронем другие не менее важные и полезные возможности Windows PowerShell.

Основы Windows PowerShell для начинающих

Содержание

  1. Что способствовало появлению Windows PowerShell?
  2. Что такое Windows PowerShell?
  3. Версии Windows PowerShell
  4. Язык PowerShell
  5. Оболочка Windows PowerShell
  6. Командлеты в PowerShell
  7. Конвейер в PowerShell
  8. Фоновое исполнение заданий
  9. Удаленное управление на PowerShell
  10. Сценарии, функции и модули в Windows PowerShell
  11. Интегрированная среда сценариев Windows PowerShell (ISE)

До появления PowerShell существовали (и существуют) следующие инструменты для автоматизации и администрирования сервисов: командная строка Windows и Windows Script Host. Но у этих технологий есть недостатки.

У командной строки Windows есть и возможность выполнять какие-то административные задачи и возможность записать алгоритм действий, сохранив его в виде скрипта (bat-файла), при этом можно использовать некие элементы программирования, например, использовать переменные, условные конструкции и даже что-то вроде циклов.

Большинство программных продуктов имеет консольный интерфейс, т.е. мы можем управлять программой, используя командную строку, при этом экономя ресурсы за счет отсутствия затрат на работу графического интерфейса. Компания Microsoft для серверной операционной системы Windows Server даже выпускает редакции без графического интерфейса (Server Core, в Windows Server 2019), но всего этого недостаточно, так как возможности командной строки ограничены, т.е. написать какую-то сложную логику для автоматизации чего-либо мы не сможем, а если и сможем, то на это нам потребуется время и знания.

Также недостатком командной строки является то, что для полноценного управления сервером мы используем различные консольные утилиты программных продуктов, и поэтому использовать командную строку для администрирования на самом деле сложно, с точки зрения того, что у всех этих утилит разный синтаксис, параметры, методы использования и для того чтобы выполнять типовые задачи, т.е. каждодневные, приходиться держать все это в памяти, а для выполнения нетиповых задач приходиться сначала почитать справку или документацию.

Технология Windows Script Host позволяет выполнять все административные задачи, что и командная строка, включая их автоматизацию путем написания WSH скриптов, но здесь мы уже можем использовать полноценные языки программирования (VBScript и JScript), т.е. можно реализовывать сложную логику и алгоритмы. К тому же с помощью WSH мы управляем программными продуктами через объектный интерфейс, другими словами Windows Script Host намного «круче» чем командная строка. Но данная технология также не стала тем идеальным инструментом администрирования и автоматизации этого администрирования для системных администраторов, так как Windows Script Host требовал знаний вышеперечисленных языков программирования, что для системных администраторов на самом деле лишнее. Администраторам нужно всего лишь простой инструмент администрирования с возможностью запрограммировать какие-то действия, а углубляться в объектные модели программных продуктов на языках программирования VBScript и JScript им не хочется.

В итоге компании Microsoft необходимо было разработать такой инструмент администрирования для системных администраторов, который бы на 100 процентов удовлетворял все потребности сисадминов как в плане возможностей администрирования и автоматизации, так и в плане удобства и простоты использования, таким образом, появился Windows PowerShell.

Заметка! Курсы по SQL для начинающих на примере Microsoft SQL Server.

Скриншот 1

Windows PowerShell – это язык сценариев и командная оболочка Windows, которые разработаны для администрирования и конфигурирования операционных систем Windows.

PowerShell разработан на основе среды CRL и платформы .NET Framework и в отличие от командной строки, которая принимает и возвращает текст, Windows PowerShell работает с объектами. У каждого объекта в PowerShell есть свойства и методы, которые можно использовать для управления этими объектами.

В Windows PowerShell Microsoft разработала концепцию командлетов (cmdlets), которая представляет собой систему именования команд «Глагол-Существительное». Данная система позволяет системным администраторам быстрей освоить и упростить работу с PowerShell.

С помощью Windows PowerShell можно:

  • Получать доступ к файловой системе;
  • Управлять реестром;
  • Управлять службами;
  • Управлять процессами;
  • Настраивать операционную систему;
  • Устанавливать программное обеспечение;
  • Устанавливать роли и компоненты сервера;
  • Осуществлять администрирование и конфигурирование ролей и компонентов сервера;
  • Писать и использовать сценарии для автоматизации управления и администрирования;
  • Выполнять другие задачи системных администраторов.

Windows PowerShell содержит многие часто используемые утилиты и команды, запускаемые из командной строки, например ipconfig, ping и другие. Сделано это для того, чтобы облегчить переход системных администраторов с командной строки на PowerShell.

Также для удобства многие часто используемые команды и утилиты в PowerShell имеют синонимы (Alias), например cls — это синоним командлета Clear-Host, dir синоним Get-ChildItem (полный список синонимов можно посмотреть путем запуска командлета Get-Alias).

Для упрощения поиска нужной команды в PowerShell есть специальный командлет Get-Command, с помощью которого можно осуществлять поиск, как по глаголу, так и по существительному. Все команды в Windows PowerShell сгруппированы в модули (например, Hyper-V, NetTCPIP), что также упрощает поиск нужной команды.

После того как нужная команда найдена, можно посмотреть инструкцию по работе с этой командой, т.е. справку, для этих целей есть специальный командлет Get-Help, например следующая команда покажет справку по командлету Get-Command:

  
   Get-Help Get-Command

Справка в Windows PowerShell может быть краткой, детальной (параметр -Detailed), полной (параметр -Full), а также можно выводить только примеры (параметр — Examples). Следующая команда покажет только примеры использования командлета Get-Command:

  
   Get-Help Get-Command -Examples

Справка PowerShell обновляемая, т.е. ее можно обновить командой Update-Help.

Заметка! Бесплатная система мониторинга IT инфраструктуры.

Версии Windows PowerShell

Первая версия PowerShell 1.0 появилась 14 ноября 2006 года и выпускалась в виде отдельного дистрибутива, который можно было установить на следующие версии операционных систем Windows: Windows XP Service Pack 2, Windows Server 2003 Service Pack 1 и Windows Vista.

В Windows Server 2008 PowerShell 1.0 поставлялся в виде компонента, который также нужно было устанавливать.

Начиная с Windows 7 и Windows Server 2008 R2, PowerShell поставляется как неотъемлемый компонент системы (т.е. предустановленный, устанавливать его не надо). Ниже представлена таблица соответствия версии PowerShell и версии операционной системы Windows (т.е. какая версия PowerShell по умолчанию установлена в той или иной версии Windows):

Версия PowerShell Версии Windows
PowerShell 2.0 Windows 7, Windows Server 2008 R2
PowerShell 3.0 Windows 8, Windows Server 2012
PowerShell 4.0 Windows 8.1, Windows Server 2012 R2
PowerShell 5.0 Windows 10, Windows Server 2016

С каждой новой версией PowerShell становится все более мощным инструментом администрирования, для сравнения в первой PowerShell было около 130 командлетов, а в PowerShell 5.0 их уже более 600!

Узнать текущую версию PowerShell можно с помощью свойства PSVersion встроенной переменной $PSVersionTable, например, выполните следующую команду:

  
   $PSVersionTable.PSVersion

Или запустите командлет

  
   Get-Variable -Name PSVersionTable –ValueOnly

где, значение PSVersion и будет версией PowerShell.

Язык PowerShell

PowerShell – это объектно-ориентированный скриптовой язык программирования.

Он используется для написания команд управления всеми компонентами операционной системы Windows в оболочке Windows PowerShell, а также для написания сценариев автоматизации задач администрирования в интегрированной среде сценариев Windows PowerShell (ISE). Язык PowerShell хоть и создан для задач администрирования, он является полноценным скриптовым языком программирования, так как имеет программные конструкции, которые присутствуют в каждом языке программирования, такие как: условия, циклы, обработка ошибок, работа с переменными, объектами, массивами.

Язык PowerShell имеет единый синтаксис написания команд и структуру именования этих команд по принципу «Глагол-Существительное», что делает данный язык интуитивно понятным как для программистов, так и для системных администраторов.

Более подробно о программировании на данном языке можете посмотреть в материале — Программирование на языке PowerShell.

Оболочка Windows PowerShell

Оболочка Windows PowerShell – это среда выполнения команд и сценариев на языке PowerShell.

Данная оболочка имеет те же возможности что и командная строка такие как: хранение истории выполнения команд, настройка внешнего вида оболочки, завершение выполнения команд сочетанием клавиш Ctrl+C, а также много других возможностей, которых нет в оболочке командной строки, например такая замечательная возможность как «подсветка синтаксиса» (появилась в PowerShell 5.0).

Запустить оболочку PowerShell можно несколькими способами, например:

  • Из командной строки, набрав PowerShell;
  • Через диалоговое окно «Выполнить» (сочетание клавиш Win+R), также набрав PowerShell;
  • В Windows 7 — Пуск->Все программы ->Стандартные ->Windows PowerShell -> Windows PowerShell;
  • В Windows 8.1 или Windows Server 2012 R2 — Пуск->Все программы ->Служебные ->Windows PowerShell;
  • В Windows 10 или Windows Server 2016 — Пуск->Все программы -> Каталог Windows PowerShell (в группе W) -> Windows PowerShell.

Пример запуска PowerShell в Windows Server 2016

Скриншот 2

Заметка! ТОП 7 популярных языков программирования.

Скриншот оболочки PowerShell в Windows Server 2016

Скриншот 3

Командлеты в PowerShell

Командлет (cmdlet) – это команда Windows PowerShell, с помощью которой можно осуществлять взаимодействие с объектами операционной системы с целью их управления.

Данные команды являются частью языка PowerShell. Командлеты построены по принципу «Глагол-Существительное», разделенные дефисом (-); другими словами, мы сначала указываем, что делать, а через дефис — над чем. Например, командлет Get-Help, где Get — это глагол, означающий «Получить», а Help — существительное «Помощь» в контексте PowerShell «Показать – Справку». Командлеты PowerShell возвращают результаты в виде объектов, что является одним из главных отличий от командной строки Windows, в которой команды возвращают только текст на экран.

Кроме командлетов на получение данных (Get), существуют и такие типы командлетов как:

  • Add – добавление данных;
  • Clear – очистить;
  • Enable – включить;
  • Disable – выключить;
  • New – создать;
  • Remove – удалить;
  • Set – задать;
  • Start — запустить;
  • Stop – остановить;
  • Export – экспортировать;
  • Import – импортировать;
  • И еще много других.

Полный список командлетов в Windows PowerShell можно посмотреть с помощью специального командлета Get-Command. Например, запустите его с параметром -CommandType cmdlet, в итоге на экране у Вас отобразится список командлетов.

  
   Get-Command -CommandType cmdlet

Как Вы уже поняли, у командлетов есть параметры, с помощью которых мы можем конкретизировать действия командлета. Параметры бывают обязательные и необязательные, например, у командлета Get-Command обязательных параметров нет.

Ниже на картинке представлен способ поиска командлета по глаголу (параметр Verb). В данном случае у нас отобразился список командлетов, которые умеют что-то перезапускать.

Скриншот 4

Команда

Курс по SQL для начинающих

  
   Get-Command -Verb Restart

Для поиска командлета по существительному необходимо использовать параметр Noun. Например, ниже мы получили список командлетов, которые работают со службами.

Скриншот 5

Команда

  
   Get-Command -Noun Service

Если Вы не нашли нужный командлет по полному названию можете использовать маску в формате *Текст*.

Конвейер в PowerShell

Одной из главных возможностей Windows PowerShell является возможность использования конвейера при выполнении команд.

Конвейер – это передача результата работы командлета через вертикальную черту (|) другому командлету.

При этом, как Вы помните, в PowerShell командлеты работают с объектами и возвращают объекты, соответственно по конвейеру передаются также объекты.

С помощью конвейера можно выполнять сложные задачи простым и удобным способом без необходимости написания сложных алгоритмов и сценариев.

Например, давайте узнаем название самого большого файла в каталоге «C:WindowsSystem32» (простой пример конвейера).

Скриншот 6

Команда

  
   Get-ChildItem -Path "C:WindowsSystem32" -File | Sort-Object length -Descending | Select-Object -First 1

Где,

  • Get-ChildItem – командлет получения объектов в указанном каталоге;
  • Sort-Object – командлет для сортировки объектов, в нашем случае мы сортируем по размеру файла (length -Descending);
  • Select-Object – командлет выбора нужных свойств объекта, в нашем случае мы выводим стандартные поля и только самый первый объект, т.е. большой файл (параметр -First 1).

Все командлеты отделены друг от друга вертикальной чертой. Результат работы каждого командлета передается на вход другому командлету, т.е. сначала мы получаем все объекты в указанном каталоге, затем сортируем полученный результат и в заключение выбираем самый первый объект.

Фоновое исполнение заданий

В Windows PowerShell есть возможность фонового исполнения заданий, она представляет собой механизм, с помощью которого можно запустить на выполнение команду (например, которая долго выполняется) в фоновом режиме, т.е. после запуска Вы возвращаетесь в текущую сессию и можете продолжить работу, не дожидаясь окончания работы команды. Данная возможность Вам понадобится тогда, когда у Вас возникнет необходимость запустить команду, работа которой занимает достаточно продолжительное время, а как Вы знаете, в течение этого времени сессия оболочки PowerShell блокируется до завершения работы команды, а Вам нужно продолжать работать.

Всеми заданиями, которые запущенны в фоновом режиме, Вы можете управлять, например, посмотреть список заданий, остановить работу задания, удалить задание, и, конечно же, посмотреть результат работы задания.

В Windows PowerShell для работы с фоновыми заданиями есть следующие командлеты:

  • Start-Job – запустить фоновую задачу;
  • Stop-Job – остановить фоновую задачу
  • Get-Job – посмотреть список фоновых задач;
  • Receive-Job – посмотреть результат выполнения фоновой задачи;
  • Remove-Job – удалить фоновую задачу;
  • Wait-Job – перевести фоновую задачу на передний план, для того чтобы дожидаться ее окончания.

Для запуска в фоновом режиме необходимо написать команду Start-Job, а в фигурных скобках {} команду или набор команд, которые необходимо выполнить в фоновом режиме.

Например, давайте запустим какую-нибудь задачу (показать список служб) в фоновом режиме, затем посмотрим на список фоновых заданий и выведем на экран результат работы нашего задания (т.е. список служб).

Запуск задачи в фоновом режиме

  
   Start-Job {Get-Service}

Смотрим на список задач запущенных в фоновом режиме

  
   Get-Job

Отображаем результат работы задания Job1

  
   Receive-Job Job1

Скриншот 7

Как видим, у нас появилась задача со статусом «Completed», т.е. она уже выполнилась (просто Get-Service отрабатывает быстро).

Для того чтобы посмотреть результат работы фоновой задачи, т.е. командлета Get-Service, мы выполнили команду Receive-Job и передали ей имя задания (можно и значение идентификатора). В результате у нас отобразился список служб.

Заметка! Рейтинг популярности антивирусов для домашних компьютеров.

Удаленное управление на PowerShell

Windows PowerShell рассчитан не только на локальное использование, но и на удаленное выполнение команд. Данная возможность необходима, чтобы Вы могли со своего рабочего места управлять удаленными компьютерами, т.е. выполнять команды PowerShell.

Существует несколько способов удаленного управления:

  • С помощью параметра –ComputerName (есть у многих команд). Другими словами Вы передаете имя компьютера, на котором необходимо выполнить команду, в качестве параметра. Способ обладает недостатком, так как ограничивается выполнением одной команды;
  • С помощью сессий. Командлет Enter-PSSession (интерактивный сеанс). Таким способом Вы подключаетесь к удаленному компьютеру и все команды, которые Вы будете набирать в оболочке PowerShell, будут выполняться на удаленном компьютере так же, как если бы Вы набирали команды непосредственно на удаленном компьютере. Способ также обладает недостатком, так как сеанс ограничивается одним компьютером;
  • С помощью командлета Invoke-Command. С помощью данного способа можно выполнять команды или сценарии как на одном компьютере, так и на нескольких.

Например, чтобы подключиться к удаленному компьютеру (в примере ниже ServerName) интерактивным сеансом выполните следующую команду:

  
   Enter-PSSession ServerName

Сценарии, функции и модули в Windows PowerShell

Если Вы написали некий алгоритм, скорей всего Вы захотите сохранить его, для того чтобы в дальнейшем им пользоваться. В Windows PowerShell для этих целей существует механизм использования сценариев.

Суть данного механизма следующая, Вы пишите нужный Вам набор команд и сохраняете его в качестве сценария — это простой текстовый файл с расширением .PS1.

Затем, для того чтобы выполнить этот сценарий, Вы просто запускаете его в оболочке PowerShell. При этом Вам необходимо либо указать полный путь к файлу сценария, либо перейти в каталог со сценарием и вызвать его по имени.

Важно!

По умолчанию выполнение сценариев в Windows запрещено! Для того чтобы посмотреть политику выполнения сценариев выполните командлет Get-ExecutionPolicy. В результате он вернет действующую политику, например:

  • Restricted – блокируется выполнение любых сценариев (значение по умолчанию);
  • AllSigned – разрешено выполнение сценариев, которые имеют цифровую подпись;
  • RemoteSigned – разрешено выполнение локальных сценариев, все скачанные сценарии должны иметь цифровую подпись;
  • Unrestricted — разрешено выполнение любых сценариев (не рекомендуется, так как небезопасно!).

Для разрешения выполнения сценариев необходимо использовать командлет Set-ExecutionPolicy с одним из вышеперечисленных параметров.

Например, для разрешения выполнения локальных сценариев выполним следующую команду, и согласимся с внесением изменений, нажав Y.

  
   Set-ExecutionPolicy RemoteSigned

В сценарии можно передавать параметры, делать их обязательными или задавать значение по умолчанию.

В Windows PowerShell предусмотрен механизм создания собственных функций, которые также как и встроенные командлеты можно будет использовать в оболочке PowerShell.

Для этого необходимо указать ключевое слово Function и затем в фигурных скобках {} написать алгоритм работы этой функции, т.е. набор команд (например, какая-нибудь часто используемая процедура: создать пользователя с определенными правами, очистить определенные каталоги и так далее). Потом необходимо сохранить все это в сценарий, но только уже с расширением .psm1, так как этот файл будет являться уже модулем.

Это еще не все, этот файл необходимо поместить в каталог, в котором PowerShell ищет модули. Таких каталогов несколько (специальный каталог в профиле пользователя, каталог, где установлен PowerShell), их можно посмотреть в переменных окружения PowerShell. Для этого выполните следующую команду

  
   Get-ChildItem Env:PSModulePath | Format-Table -AutoSize

После того как Вы поместите написанный Вами модуль в специальный каталог, Вы сможете обращаться к своим функциям как к обычным командам PowerShell.

Интегрированная среда сценариев Windows PowerShell (ISE)

Для того чтобы было удобно писать сценарии, функции и соответственно модули, компания Microsoft разработала специальную графическую программу Integrated Scripting Environment.

Integrated Scripting Environment (ISE) – интегрированная среда сценариев.

Работать в этой программе очень удобно, к тому же она имеет мощный функционал (создание множества вкладок со сценариями, область вывода, встроенный отладчик и другое).

Запустить ее можно следующим образом:

  • В Windows 7 — Пуск->Все программы ->Стандартные ->Windows PowerShell -> Windows PowerShell ISE;
  • В Windows 10 или Windows Server 2016 — Пуск->Все программы -> Каталог Windows PowerShell (в группе W) -> Windows PowerShell ISE.

Примечание! ISE не будет работать на системе Windows Server, установленной в варианте Server Core.

Скриншот интегрированной среды сценариев PowerShell (ISE) в Windows Server 2016

Скриншот 8

Заметка! ТОП 5 популярных систем управления базами данных (СУБД).

На этом у меня все, надеюсь, материал был Вам полезен! Удачи!

This article covers the differences between the PowerShell versions on different Windows versions. In a new section below, we discuss the differences of Windows PowerShell and PowerShell Core 6. In this article «Windows PowerShell» refers to the PowerShell versions that run on Windows until version 5.1. PowerShell Core or PowerShell 6 refers to the new cross-platform edition of PowerShell.

Contents

  1. Backward compatibility
  2. Check PowerShell version
  3. Switch to PowerShell 2.0
  4. PowerShell 32-bit vs. 64-bit
  5. PowerShell and Windows versions
  6. PowerShell Core, PowerShell 7 supported operating systems
  7. FAQ: Windows PowerShell vs. PowerShell Core
  8. Download Windows PowerShell
  9. Download PowerShell 7
  10. New features in PowerShell 7, PowerShell 7.1 and 7.2
  • Author
  • Recent Posts

Michael Pietroforte is the founder and editor in chief of 4sysops. He has more than 35 years of experience in IT management and system administration.

Please edit this document if you spot an error or if you want to add information.

Backward compatibility

Windows PowerShell is backward compatible with previous versions of Windows PowerShell. Thus, it makes sense to update all machines in your network to the latest Windows PowerShell version. If you use features in a script of a newer PowerShell version on an outdated system, your script will fail. You can easily deploy PowerShell with Group Policy. Note that PowerShell 7 is not fully backward compatible with Windows PowerShell. For more information read PowerShell v5 vs. PowerShell v7—Which to use and when

The Windows PowerShell Compatibility Pack is already available in the PowerShell Gallery. It allows you to import existing modules in PowerShell 6.x and use them like if you are in a PowerShell for Windows console. However, you must be aware that this works fine with a lot of modules but not with all of them. It’s up to you to try which modules can be used with this method or not.

To download and install the module on a computer

Install-Module -Name WindowsCompatibility -Repository PSGallery

After that, you just have to import the WindowsCompatibility module once per session and use the Import-WinModule cmdlet for every non-compatible module you want to run on PowerShell 6.x

PS C:> Import-Module -Name WindowsCompatibility
PS C:> Import-WinModule -Name MyModuleWhichIsNotCompatible
PS C:>

Check PowerShell version

If you want to know what PowerShell version you are using, you can run the $PSVersionTable command.

PS C:> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.15063.674
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.674
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


PS C:>

This also works with PowerShell Core on different operating systems.

PowerShell Core on macOS runs on Darwin

PowerShell Core on macOS runs on Darwin

Switch to PowerShell 2.0

PowerShell 2.0 is integrated in all Windows versions since Windows 7 and Windows Server 2008 R2. If you want to ensure that a PowerShell script also works properly on a system with PowerShell 2.0, you can switch to a PowerShell 2.0 prompt on every Windows version after Windows 7 with PowerShell.exe -Version 2. However, this will only work if you installed .NET Framework 2.0 / 3.5.

PowerShell 32-bit vs. 64-bit

On a Windows 64-bit edition, you will find a 32-bit and a 64-bit version of PowerShell for backward compatibility purposes. If you type “PowerShell” on a Windows Start Screen, you will see “x86” behind the 32-bit versions of PowerShell and PowerShell ISE.

PowerShell (x86)

By and large, the 64-bit and 32-bit PowerShell versions are compatible, and you shouldn’t notice much of a difference. Problems can arise if binaries are involved. For instance, if you want to extend PowerShell with snap-ins (compiled cmdlets), you have to ensure that you download the correct version. You can also run into problems if you want to instantiate an object of a 32-bit application (Microsoft Office, for example) with the 64-bit version of PowerShell.

You can check whether you are in 32-bit or 64-bit shell with [Environment]::Is64BitProcess. If you are running PowerShell 64-bit, you will receive True as output; otherwise, you’ll receive False.

PowerShell Process 32-bit or 64-bit

PowerShell and Windows versions

The following table gives you an overview of the Windows PowerShell versions and how they correlate to the different Windows versions. The Default Windows Versions column tells you the Windows PowerShell version that was delivered with the corresponding Windows version. The links in the Available Windows Versions column allow you to download the Windows PowerShell version for the corresponding Windows version. Note that Windows PowerShell is part of the Windows Management Framework which also includes Windows PowerShell Web Services, Windows Remote Management (WinRM), Windows Management Instrumentation (WMI), and the Server Manager WMI provider.

PowerShell Version Release Date Default Windows Versions Available Windows Versions
PowerShell 1.0 November 2006 Windows Server 2008 (*) Windows XP SP2
Windows XP SP3
Windows Server 2003 SP1
Windows Server 2003 SP2
Windows Server 2003 R2
Windows Vista
Windows Vista SP2
PowerShell 2.0 October 2009 Windows 7
Windows Server 2008 R2 (**)
Windows XP SP3
Windows Server 2003 SP2
Windows Vista SP1
Windows Vista SP2
Windows Server 2008 SP1
Windows Server 2008 SP2
PowerShell 3.0 September 2012 Windows 8
Windows Server 2012
Windows 7 SP1
Windows Server 2008 SP2
Windows Server 2008 R2 SP1
PowerShell 4.0 October 2013 Windows 8.1
Windows Server 2012 R2
Windows 7 SP1
Windows Server 2008 R2 SP1
Windows Server 2012
PowerShell 5.0 February 2016 Windows 10 Windows 7 SP1
Windows 8.1
Windows Server 2012
Windows Server 2012 R2
PowerShell 5.1 January 2017 Windows 10 Anniversary Update
Windows Server 2016
Windows 7 SP1
Windows 8.1
Windows 10
Windows 11
Windows Server 2008 R2 SP1
Windows Server 2012
Windows Server 2012 R2
Windows Server 2019
Windows Server 2022
PowerShell Core 6 January 2018 N/A Windows 7 SP1
Windows 8.1
Windows Server 2008 R2 SP1
Windows Server 2012
Windows Server 2012 R2
PowerShell 7 March 2020 N/A Windows 7 SP1
Windows 8.1
Windows 10
Windows 11
Windows Server 2008 R2 SP1
Windows Server 2012
Windows Server 2012 R2
Windows Server 2019
Windows Server 2022

* Has to be installed through Server Manager
** Also integrated in all later Windows versions

PowerShell Core is the successor of Windows PowerShell 5.1 and runs on Windows, Linux and macOS. The table below lists all supported operating systems and the FAQ at the end of this article answers important questions about the difference between Windows PowerShell and PowerShell Core.

PowerShell Core, PowerShell 7 supported operating systems

OS Windows PowerShell 5.1 PowerShell Core 6.0 PowerShell Core 6.1 PowerShell 7
Windows Windows 7 SP1

Windows 8.1

Windows 10

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2019

Windows Server 2022

Windows Server 2016

Windows 7 SP1

Windows 8.1

Windows 10

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2016

Windows 7 SP1

Windows 8.1

Windows 10 1607+

Windows 11

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2016

Windows Server 2019

Windows Server 2022

Windows 7 SP1

Windows 8.1

Windows 10

Windows Server 2008 R2 SP1+

Windows Server 2012

Windows Server 2012 R2

Windows Server 2016

Windows Server 2019

Windows Server 2022

macOS 10.12+ 10.12+ 10.13+
Red Hat Enterprise Linux 7 7 7
CentOS 7 7 7
Oracle Linux 7
Fedora 25, 26 27, 28 29+
Debian 8.7+, 9 8.7+, 9 9+
Ubuntu 14.04, 16.04, 17.04 18, 17 18.10 16.04+
openSUSE 42.2+ 42.2+ 15+
Arch Linux N/A N/A N/A
Kali N/A N/A N/A
Raspbian N/A (ARM32) N/A
Alpine (experimental Docker image coming soon) 3.8+

FAQ: Windows PowerShell vs. PowerShell Core

Does Windows PowerShell have a future?

No, the future belongs to PowerShell Core. As things stand now, Microsoft will only provide bug fixes and security updates for Windows PowerShell. Only PowerShell Core will receive feature updates.

Should I still work with Windows PowerShell or switch to PowerShell 7 now?

This depends on your environment. If all of your systems have PowerShell 7  installed, you might consider moving now. However, PowerShell 7 still has compatibility issues with some modules. Thus, you should have to make sure first that all required modules are available. For more information read this article:

PowerShell v5 vs. PowerShell v7—Which to use and when

Can I run Windows PowerShell and PowerShell 7 on the same Windows computer?

Yes

Can I use PowerShell ISE with PowerShell Core?

No, use Visual Studio Code instead for PowerShell Core.

Will all of my old Windows PowerShell scripts work on PowerShell Core, that is, is PowerShell 7 backward compatible with Windows PowerShell?

Previous PowerShell updates were fully backward compatible. This only applies partly to PowerShell 7. Because PowerShell 7 is a cross-platform edition of PowerShell, Microsoft made a few compromises. This means you have to test each and every Windows PowerShell script to make sure it also works on PowerShell 7.

Will all scripts I write for PowerShell 7 run on all supported platforms?

Basic scripts will run on all platforms. However, considering the huge differences between the supported platforms, you have to test each script on all platforms it is supposed to run on.

Do all modules for Windows PowerShell run on PowerShell 7?

No, many complex modules have to be adapted for PowerShell 7. In some cases, different module versions exist for both PowerShell editions.

Why can’t I launch PowerShell 7 with powershell.exe on a Windows computer?

This is because PowerShell Core and Windows PowerShell have to coexist on Windows computers. You can start PowerShell Core with the pwsh command.

I can’t find the official documentation for PowerShell 7. Where is it?

Microsoft has merged the Windows PowerShell documentation with the PowerShell 7 documentation.
You can find it here.

I have an unanswered question about the differences between PowerShell 7 and Windows PowerShell. Where can I ask it?

Ask in the PowerShell forum.

Should I extend this FAQ by editing this wiki doc?

Definitely, yes!

Download Windows PowerShell

Windows PowerShell is part of the Windows Management Framework. Below all the download links of the different Windows PowerShell versions. To test your script on PowerShell 2.0, please the corresponding section above.

PowerShell 3.0 — Windows Management Framework 3.0

PowerShell 4.0 — (Windows Management Framework 4.0

PowerShell 5.0 — Windows Management Framework 5.0

PowerShell 5.1 — Windows Management Framework 5.1

Download PowerShell 7

You can download PowerShell for every operating system here.

New features in PowerShell 7, PowerShell 7.1 and 7.2

Please read the articles below for more information about the new features in PowerShell 7, PowerShell 7.1 and PowerShell 7.2

Top 10 new features of PowerShell 7

PowerShell v5 vs. PowerShell v7—Which to use and when

How to install PowerShell 7 on Windows and Linux

New features in PowerShell 7.1

How to install and upgrade to PowerShell 7.1

PowerShell 7.2: New features in the Preview

Главная / Операционные системы /
Командная строка и сценарии Windows / Тест 1

Упражнение 1:


Номер 1

В каких версиях операционной системы Windows можно пользоваться командными файлами?

Ответ:

(1) во всех версиях Windows 

(2) в Windows NT и выше 

(3) в Windows XP и выше 


Номер 2

Какие версии операционной системы Windows поддерживают сервер сценариев WSH?

Ответ:

(1) Windows 2000 и выше 

(2) все 32-разрядные версии Windows 

(3) Windows NT и выше 


Номер 3

Какие версии операционной системы Windows поддерживают оболочку PowerShell?

Ответ:

(1) Windows XP SP2 и выше 

(2) все 32-разрядные версии Windows 

(3) Windows 2000 и выше 


Упражнение 2:


Номер 1

Какие средства позволяют напрямую обращаться к объектам WMI?

Ответ:

(1) оболочка WMIC 

(2) сценарии WSH 

(3) интерпретатор Cmd.exe 


Номер 2

Какие средства позволяют напрямую обращаться к объектам .NET?

Ответ:

(1) оболочка WMIC 

(2) сценарии WSH 

(3) оболочка Windows PowerShell 


Номер 3

Какие средства позволяют обращаться к объектам WMI непосредственно из командной строки?

Ответ:

(1) оболочка WMIC 

(2) оболочка Windows PowerShell 

(3) интерпретатор Cmd.exe 


Упражнение 3:


Номер 1

Какие языки можно использовать для написания сценариев WSH?

Ответ:

(1) Microsoft VBScript 

(2) Microsoft JScript 

(3) Microsoft C# 


Номер 2

Можно ли написать сценарий WSH на языке Perl?

Ответ:

(1) нет 

(2) да, Perl поддерживается по умолчанию 

(3) да, но требуется установка специального модуля поддержки Perl 


Номер 3

Какие языки можно использовать для написания сценариев PowerShell?

Ответ:

(1) Microsoft VBScript 

(2) собственный язык Windows PowerShell 

(3) Microsoft C# 


Упражнение 4:


Номер 1

Какое средство автоматизации предлагает собственную объектную модель?

Ответ:

(1) Cmd.exe 

(2) Windows PowerShell 

(3) WSH 


Номер 2

Можно ли написать сценарий WSH на языке Python?

Ответ:

(1) нет 

(2) да, Python поддерживается по умолчанию 

(3) да, но только после установки модуля поддержки Python 


Номер 3

Какие средства позволяют обращаться к объектам COM непосредственно из командной строки?

Ответ:

(1) сценарии WSH 

(2) оболочка Windows PowerShell 

(3) интерпретатор Cmd.exe 


Упражнение 5:


Номер 1

Можно ли в Windows использовать стандартные Unix-утилиты?

Ответ:

(1) да, после установки пакета Services for Unix  

(2) да, Unix-утилиты поддерживаются по умолчанию 

(3) нельзя 


Номер 2

Какие средства позволяют управлять приложениями-серверами автоматизации?

Ответ:

(1) оболочка Windows PowerShell 

(2) сценарии WSH 

(3) оболочка Cmd.exe 


Номер 3

Какие средства позволяют управлять серверами автоматизации в интерактивном режиме?

Ответ:

(1) оболочка Windows PowerShell 

(2) сценарии WSH 

(3) оболочка Cmd.exe 


Упражнение 6:


Номер 1

Какие из средств автоматизации поддерживают работу в интерактивном режиме?

Ответ:

(1) WSH 

(2) WMIC  

(3) Windows PowerShell 


Номер 2

Какие из средств автоматизации являются оболочками командной строки?

Ответ:

(1) Cmd.exe 

(2) WSH  

(3) Windows PowerShell 


Номер 3

Какие средства автоматизации имеют встроенную справочную систему?

Ответ:

(1) интерпретатор Cmd.exe 

(2) WSH 

(3) Windows PowerShell 


Windows PowerShell

Шаблон:Wikidata/p154
Шаблон:Wikidata/p18
Сессия в Windows PowerShell.
Тип

Ошибка Lua: callParserFunction: function «#property» was not found.

Автор

Ошибка Lua: callParserFunction: function «#property» was not found.

Разработчик

Microsoft

Написана на

Ошибка Lua в Модуль:Wikidata на строке 170: attempt to index field ‘wikibase’ (a nil value).

Интерфейс

Ошибка Lua в Модуль:Wikidata на строке 170: attempt to index field ‘wikibase’ (a nil value).

Операционная система

Ошибка Lua: callParserFunction: function «#property» was not found.

Языки интерфейса

Ошибка Lua в Модуль:Wikidata на строке 170: attempt to index field ‘wikibase’ (a nil value).

Первый выпуск

Шаблон:Wikidata/p577

Аппаратная платформа

Ошибка Lua: callParserFunction: function «#property» was not found.

Последняя версия

Шаблон:Wikidata/p348

Кандидат в релизы

Шаблон:Wikidata/p348

Бета-версия

Шаблон:Wikidata/p348

Альфа-версия

Шаблон:Wikidata/p348

Тестовая версия

Шаблон:Wikidata/p348

Читаемые форматы файлов

Ошибка Lua в Модуль:Wikidata на строке 170: attempt to index field ‘wikibase’ (a nil value).

Создаваемые форматы файлов

Ошибка Lua в Модуль:Wikidata на строке 170: attempt to index field ‘wikibase’ (a nil value).

Лицензия

Ошибка Lua: callParserFunction: function «#property» was not found.

Сайт

Шаблон:Wikidata/p856

Шаблон:Wikidata/p373

Шаблон:Нет изображенияШаблон:Категория по дате

Windows PowerShell — расширяемое средство автоматизации от Microsoft, состоящее из оболочки с интерфейсом командной строки и сопутствующего языка сценариев. Впервые публично язык был продемонстрирован на Профессиональной конференции разработчиков (Шаблон:Lang-en, PDC) в сентябре 2003 года под кодовым названием Monad.

Windows PowerShell 2.0 был выпущен в составе Windows 7, Windows 8 и Windows Server 2008 R2, а также Windows Server 2012 R2, как неотъемлемый компонент системы. Кроме того, вторая версия доступна и для других систем, таких, как Windows XP SP3, Windows Server 2003 SP2, Windows Vista SP1, Windows Vista SP2, Windows Server 2008[1] и Windows Server 2012.

Windows PowerShell построен на базе Microsoft .NET Framework и интегрирован с ним. Дополнительно PowerShell предоставляет удобный доступ к COM, WMI и ADSI, равно как и позволяет выполнять обычные команды командной строки, чтобы создать единое окружение, в котором администраторы смогли бы выполнять различные задачи на локальных и удалённых системах.

Эти административные задачи обычно выполняются с помощью командлетовШаблон:Переход (в оригинале Шаблон:Lang-en2), которые являются специализированными классами .NET. Пользователь может комбинировать их в скриптах (сценариях), используя различные конструкции, утилиты командной строки и обращения к обычным классам .NET, объектам WMI или COM. Кроме того, можно использовать различные хранилища данных, такие, как файловая система или реестр Windows, которые предоставляются PowerShell посредством поставщиков (Шаблон:Lang-en).

Windows PowerShell также предоставляет механизм встраивания, благодаря которому исполняемые компоненты PowerShell могут быть встроены в другие приложения. Эти приложения затем могут использовать функциональность PowerShell для реализации различных операций, включая предоставляемые через графический интерфейс. Этот подход применён в Microsoft Exchange Server 2007 для реализации управляющей функциональности в виде командлетов PowerShell и графических утилит управления в виде оболочек PowerShell, которые вызывают необходимые командлеты. Таким образом, графический интерфейс управления находится поверх промежуточного слоя — PowerShell. Другие приложения Microsoft, включая Microsoft SQL Server 2008, System Center Operations Manager и System Center Data Protection Manager также предоставляют доступ к своим интерфейсам управления через командлеты PowerShell.

Windows PowerShell включает свою собственную расширяемую справку, доступную (в том числе из командной строки) через командлет Get-Help.

Предыстория[]

Каждая выпущенная версия MS-DOS и Microsoft Windows для персональных компьютеров содержала утилиту, предоставляющую интерфейс командной строки. Это были COMMAND.COM (в системах, основанных на MS-DOS, включая Windows 9x) и cmd.exe (в системах семейства Windows NT). Это были обычные интерпретаторы командной строки, имевшие лишь несколько базовых команд. Для других задач требовались отдельные консольные приложения, которые вызывались из этих оболочек. Они также имели язык сценариев (пакетные файлы), при помощи которого можно было автоматизировать различные задачи. Однако эти интерпретаторы не годились для полноценной автоматизации — частично потому, что в них отсутствовали эквиваленты многих операций графического интерфейса, а также из-за слабой функциональности языка сценариев, не позволявшего описывать достаточно сложные алгоритмы. В Windows Server 2003 ситуация была улучшена, однако поддержка сценариев всё ещё считалась недостаточной.

Microsoft пыталась решить некоторые из этих недостатков с помощью Windows Script Host, вышедшего в 1998 году в составе Windows 98, и утилиты для работы с ним из командной строки cscript.exe. Он интегрируется с Active Script и позволяет писать сценарии на совместимых языках, таких, как JScript и VBScript, используя API, предоставляемое приложениями через Component Object Model (COM). Однако у этого решения свои недочёты. Windows Script Host не интегрирован с оболочкой, отсутствует встроенная документация. Различные версии Windows также предоставляют командные интерпретаторы специального назначения (такие, как netsh.exe и WMIC) со своими собственными наборами команд. Они не интегрированы с командной оболочкой и не дают возможностей для взаимодействия.

В 2003 Microsoft начала разработку новой оболочки, называемой Monad (также известной как Microsoft Shell или MSH). Monad должен был стать новой расширяемой оболочкой командой строки, со свежим дизайном, который позволял бы автоматизировать весь спектр административных задач. Microsoft опубликовала первую публичную бета-версию Monad 17 июня 2005 года. Вторая и третья бета-версии были выпущены 11 сентября 2005 и 10 января 2006 соответственно. 25 апреля 2006 года было объявлено, что Monad переименован в Windows PowerShell для позиционирования его в качестве значительной части их технологий управления. В это же время была выпущена версия Release Candidate 1 («кандидат на выпуск»). Release Candidate 2 последовал 26 сентября 2006 года. Финальная версия (Release to Web, RTW) была выпущена 14 ноября 2006 года для Windows XP SP2 и Windows 2003. Финальная версия для Windows Vista стала доступна только 30 января 2007 года.

Последний CTP выпуск Windows PowerShell версии 2.0 был выпущен в декабре 2008 года. Финальная версия второй версии PowerShell была выпущена в составе систем Windows 7 и Windows Server 2008 R2 одновременно с их выпуском. Для остальных систем (Windows XP, Windows Server 2003, Windows Vista, Windows 2008), вторая версия PowerShell стала доступна в составе комплекта Windows Management Framework 27 октября 2009 года. Кроме Windows PowerShell второй версии, в этот комплект также входят WinRM версии 2.0 и BITS 4.0 (последний доступен только для Windows Vista и Windows 2008; в Windows 7 и Windows Server 2008 R2 он встроен).

Обзор[]

Команды, исполняемые в Windows PowerShell, могут быть в форме командлетов, которые являются специализированными классами .NET, созданными с целью предоставления функциональности в PowerShell в виде сценариев PowerShell (.PS1) или являются обычными исполняемыми файлами. Если команда является исполняемым файлом, то PowerShell запускает её в отдельном процессе; если это командлет, то он исполняется внутри процесса PowerShell. PowerShell предоставляет интерфейс командной строки, в котором можно вводить команды и отображать выводимые ими данные в текстовом виде. Этот пользовательский интерфейс, базирующийся на стандартном механизме консоли Windows, предоставляет настраиваемый механизм автозавершения команд, но не обладает возможностью подсветки синтаксиса, хотя при желании её можно обеспечить[2]. В PowerShell также можно создавать псевдонимы (Шаблон:Lang-en) для командлетов, которые при вызове преобразуются в оригинальные команды. Кроме того, поддерживаются позиционные и именованные параметры для командлетов. При выполнении командлета работа по привязке значений аргументов к параметрам выполняется самим PowerShell, но при вызове внешних исполняемых файлов аргументы передаются им для самостоятельного разбора.

Другое понятие, используемое в PowerShell, — это конвейер (Шаблон:Lang-en). Подобно конвейерам в UNIX, они предназначены для объединения нескольких команд путём передачи выходных данных одной команды во входные данные второй команды, используя оператор |. Но, в отличие от аналога в UNIX, конвейер PowerShell является полностью объектным, то есть данные между командлетами передаются в виде полноценных объектов соответствующих типов, а не как поток байтов. Когда данные передаются как объекты, содержащиеся в них элементы сохраняют свою структуру и типы между командлетами, без необходимости использования какой-либо сериализации или посимвольного разбора данных. Объект также может содержать некоторые функции, предназначенные для работы с данными. Они также становятся доступными для получающего их командлета. Вывод последнего командлета в конвейере PowerShell автоматически передаёт на командлет Write-Host, который создаёт текстовое представление объектов и содержащихся в них данных и выводит его на экран.

Так как все объекты PowerShell являются объектами .NET, они содержат метод .ToString(), возвращающий текстовое представление данных объекта. PowerShell использует этот метод для преобразования объекта в текст. Кроме того, он позволяет указать правила форматирования, так что текстовое представление объектов может быть настроено. Однако с целью поддержания совместимости, если в конвейере используется внешний исполняемый файл, то он получает текстовый поток, представляющий объект, и не интегрируется с системой типов PowerShell.

Расширенная система типов (Шаблон:Lang-en, ETS) PowerShell базируется на системе типов .NET, но реализует некоторые дополнения. Например, она позволяет создавать различные представления объектов, отображая лишь некоторые из их свойств и методов, а также применять специальное форматирование и механизмы сортировки. Эти представления привязываются к оригинальным объектам с помощью конфигурационных файлов в формате XML.

Командлеты[]

Командлеты (Шаблон:Lang-en) — это специализированные команды PowerShell, которые реализуют различную функциональность. Это встроенные в PowerShell команды. Командлеты именуются по правилу Глагол-Существительное, например, Get-ChildItem, благодаря чему их предназначение понятно из названия. Командлеты выводят результаты в виде объектов или их коллекций. Дополнительно командлеты могут получать входные данные в такой же форме и, соответственно, использоваться как получатели в конвейере. Хотя PowerShell позволяет передавать по конвейеру массивы и другие коллекции, командлеты всегда обрабатывают объекты поочередно. Для коллекции объектов обработчик командлета вызывается для каждого объекта в коллекции по очереди.

Экземпляры объектов создаются в PowerShell и запускаются им при вызове. Командлеты наследуются от Cmdlet или от PSCmdlet, причём последний используется тогда, когда командлету необходимо взаимодействовать с исполняемой частью PowerShell (Шаблон:Lang-en). В этих базовых классах оговорены некоторые методы — BeginProcessing(), ProcessRecord() и EndProcessing(), как минимум один из которых реализация командлета должна перезаписать для предоставления своей функциональности. Каждый раз при запуске командлета эти методы вызываются PowerShell по очереди. Сначала вызывается BeginProcessing(), затем, если командлету передаются данные по конвейеру, ProcessRecord() для каждого элемента, и в самом конце — EndProcessing(). Класс, реализующий Cmdlet, должен иметь один атрибут .NET — CmdletAttribute, в котором указываются глагол и существительное, составляющие имя командлета. Популярные глаголы представлены в виде перечисления (Шаблон:Lang-en).

Реализации командлетов могут вызывать любые доступные .NET API и могут быть написаны на любом языке .NET. PowerShell также предоставляет некоторые дополнительные API, такие, как WriteObject(), которые необходимы для доступа к специфичной для PowerShell функциональности, например, для вывода результирующих объектов в конвейер. Командлеты могут использовать API для доступа к данным напрямую или воспользоваться инфраструктурой поставщиков (Шаблон:Lang-en) PowerShell, которые позволяют обращаться к хранилищам данных через уникальные пути. Хранилища данных представляются через буквы дисков и иерархическую структуру внутри них (директории). Windows PowerShell поставляется с поставщиками для файловой системы, реестра Windows, хранилища сертификатов, а также для псевдонимов команд, переменных и функций. Другие приложения могут добавлять свои командлеты и поставщики для доступа к своим хранилищам данных.

В PowerShell 2.0 была добавлена возможность создания командлетов на самом PowerShell, без использования .NET-языков.

Конвейер[]

В PowerShell, как и в оболочках UNIX/Linux, присутствует конвейер. Этот конвейер служит для передачи выходных данных одного командлета во входные данные другого командлета. В частности, пользователь может вывести результаты командлета Get-Process в командлет Sort-Object (например, для сортировки процессов по дескрипторам), затем в Where-Object, чтобы отфильтровать процессы, которые, например, занимают меньше 1 МБ страничной памяти, и, в конце концов, передать результаты в командлет Select-Object, чтобы выбрать только первые 10 процессов (по количеству дескрипторов).
Концепция конвейера изначально используется в UNIX-подобных системах (см. Конвейер (UNIX)), концепция PowerShell отличается от данного. В UNIX-подобных системах вывод одной команды передаётся на следующий этап конвейера в бинарной форме, то есть являет собой фактически поток данных. Пример: dd if=/dev/zero bs=1M count=1M | bzip2 -z9 -c > ex.bz2, где поток «нулей» блоками по 1 МБ в количестве 1 миллиона раз (из устройства /dev/zero) командой dd (копирования специальных файлов) передаётся на ввод команды Bzip2, которая их сжимает максимально возможно (с точки зрения алгоритма сжатия bzip2, опция -z9) и результирующий поток передаёт на stdout (опция ), который, в свою очередь, перенаправляется в файл ex.bz2. Результатом выполнения такой относительно короткой команды станет создание архива, внутри которого будет поток нулевых байтов размером 1 терабайт. Сам процесс создания такого архива применяет в данном случае 2 последовательных конвейера.

Сценарии[]

PowerShell включает язык сценариев с динамическими типами, на котором можно реализовывать сложные операции с использованием командлетов. Язык сценариев поддерживает переменные, функции, конструкции ветвления (if-then-else) циклы (while, do, for и foreach), структурированную обработку ошибок и множество других возможностей, включая интеграцию с .NET. Переменные в PowerShell обозначаются префиксом $ перед именем; им может быть присвоено любое значение, включая вывод командлетов. Хотя сам язык не строго типизирован, внутри переменные сохраняются с их типами, которые могут быть базовыми типами (Шаблон:Lang-en) или объектами. Строки могут быть заключены в одиночные кавычки или в двойные кавычки: при использовании двойных кавычек переменные, содержащиеся в строке, будут заменены их значениями. В соответствии с синтаксисом переменных, если путь к файлу помещен в фигурные скобки с предшествующим знаком доллара (то есть ${C:foo.txt}), то это будет ссылкой на содержимое файла. Всё, что будет назначено такой переменной, будет записано в файл, и наоборот — при обращении к её содержимому будет выдано содержимое файла.

К свойствам и методам объекта можно обращаться, используя точку (.), как в синтаксисе C#. PowerShell предоставляет специальные переменные, такие, как $args, содержащую массив всех неименованных аргументов командной строки, переданных функции, или $_, ссылающуюся на текущий объект в конвейере и других конструкциях. В PowerShell также присутствуют массивы и ассоциативные массивы. Кроме того, PowerShell автоматически вычисляет арифметические выражения, введённые в командной строке, и понимает популярные аббревиатуры, такие, как GB (ГБ), MB (МБ) и KB (КБ).

В PowerShell можно создавать собственные функции, принимающие параметры, с помощью ключевого слова function. Проблема для многих начинающих — то, что функции принимают аргументы, разделённые не запятыми, а пробелами (как утилиты командной строки или командлеты):

  1. <function> <param1> <param2>: Вызывает функцию с двумя аргументами.

Эти аргументы могут быть привязаны к параметрам, указанным в объявлении функции. Также к ним можно обратиться через массив $args.

  1. <function>(<param1>, <param2>): Вызывает функцию с одним аргументом, который является массивом из двух элементов.

PowerShell позволяет вызывать любые методы .NET, заключив их пространство имён в квадратные скобки ([]), и затем используя пару двоеточий (::) для указания статического метода. Например, [System.Console]::WriteLine("PowerShell"). Объекты создаются с помощью командлета New-Object, добавлять к ним новые свойства можно, используя командлет Add-Member.

Для обработки ошибок PowerShell предоставляет механизм, основанный на .NET. В случае ошибки выдаются объекты, содержащие информацию об ошибке (объект Exception), которые перехватываются ключевым словом trap. Однако поведение при возникновении ошибок настраивается. Так, можно настроить PowerShell, чтобы в случае ошибки он молча продолжал выполнение без перехвата ошибки. Во второй версии PowerShell также была добавлена конструкция Try Catch Finally.

Сценарии, написанные в PowerShell, можно сохранять между сессиями в файлах .PS1. Затем можно использовать весь сценарий или индивидуальные функции из него. Сценарии и функции используются подобно командлетам, то есть они могут быть командами в конвейере, им можно передавать параметры. Объекты могут прозрачно передаваться между сценариями, функциями и командлетами в конвейере. Однако выполнение сценариев PowerShell по умолчанию запрещено, и его надо включить с помощью командлета Set-ExecutionPolicy. Сценарии PowerShell могут быть подписаны цифровой подписью для проверки их целостности.

Microsoft выпустила PowerShell 2.0 в составе Windows 7 и Windows Server 2008 R2. Windows PowerShell 2.0 предустановлен в этих системах. Исключением является режим установки Windows Server 2008 R2 в режиме Core, где PowerShell 2.0 можно доустановить вручную. Для более старых платформ он доступен в составе Windows Management Framework. PowerShell 2.0 вносит некоторые изменения в язык сценариев и API для встраивания, в дополнение к новым 240 командлетам.

Неполный список новых возможностей, включённых в PowerShell 2.0:

  • PowerShell Remoting. Используя WS-Management, PowerShell 2.0 позволяет вызывать сценарии и командлеты на удалённых машинах (в том числе и на нескольких одновременно), отслеживать состояние их выполнения и получать результаты в виде объектов (через сериализациюдесериализацию). Также возможно устанавливать интерактивные сессии и сессии с ограниченной функциональностью.
  • Фоновые работы. Возможность вызывать последовательности команд асинхронно. Работы можно запускать на локальной машине или на нескольких удалённых машинах. Работы не могут использовать интерактивные командлеты.
  • Транзакции. Позволяют разработчикам командлетов и поставщиков реализовывать транзакционные операции. PowerShell 2.0 включает командлеты для инициализации, подтверждения и отката транзакций и возможности для управления транзакциями и использования их в командлетах и поставщиках.
  • Advanced Functions. Возможность разрабатывать полноценные командлеты, используя только сам PowerShell.
  • SteppablePipelines. Позволяет пользователю контролировать вызов функций BeginProcessing(), ProcessRecord() и EndProcessing() при вызове командлета.
  • Модули. Позволяют авторам сценариев и администраторам организовывать сценарии PowerShell и помещать их в самодостаточные модули. Код из модуля выполняется в своем собственном, независимом контексте и не влияет на окружение вне модуля. Используя сценарий, модули могут объявлять ограниченное окружение. Модули могут содержать публичные и приватные функции и переменные.
  • Язык данных. Подмножество языка PowerShell, которое позволяет отделять определения данных от исполняемого кода сценариев и даёт возможность импортировать в сценарий локализованные строки в процессе выполнения.
  • Отладка сценариев. Возможность устанавливать точки прерывания (Шаблон:Lang-en) в сценариях или функциях PowerShell. Точки прерывания могут быть установлены на строки, столбцы, команды или операции чтения и/или записи переменных. Присутствуют командлеты для установки и контроля точек прерывания в сценариях.
  • Eventing (событирование). Эта возможность позволяет слушать, перенаправлять, и выполнять действия при возникновении событий управления или системы. Благодаря событированию хосты PowerShell могут быть оповещены о изменениях состояния в управляемых объектах. Также позволяет сценариям подписываться на ObjectEvents, PSEvents и WmiEvents и обрабатывать их синхронно и асинхронно.
  • Windows PowerShell Integrated Scripting Environment (ISE). PowerShell 2.0 включает графическую оболочку для языка, в которую входят встроенный отладчик, подсветка синтаксиса, автозавершение команд. Оболочка позволяет запускать несколько независимых консолей PowerShell с полной поддержкой Юникода в интерфейсе с закладками. Благодаря поддержке удалённого выполнения некоторые консоли могут выполняться и на других компьютерах. Кроме того, ISE позволяет выполнять только выделенные части сценариев, содержит встроенный редактор и позволяет расширять и дополнять свой интерфейс с помощью PowerShell.
  • BITS Transfer — встроенная поддержка передачи файлов по сети с приоритизацией, многопоточностью, возобновлением и асинхронной работой на основе технологии Background Intelligent Transfer Service.
  • Множество новых командлетов, включая, например, Out-GridView, позволяющий вывести результаты конвейера в графическую таблицу (на основе WPF), с возможностями сортировки и мгновенного поиска.
  • Новые операторы -Split, -Join и оператор подстановки (@).
  • Обработка ошибок с Try-Catch-Finally. В отличие от других .NET языков, в PowerShell можно указывать несколько типов исключений для одного блока catch.
  • Блочные комментарии. PowerShell 2.0 поддерживает блочные комментарии (плюс к уже имеющимся построчным #) с использованием <# и #> в качестве ограничителей.
  • Новые API добавили разные возможности, от большего контроля над парсером PowerShell до способности создавать ограниченные сессии (Шаблон:Lang-en), в которых можно выполнять лишь ограниченный набор инструкций и команд PowerShell.

Сравнение командлетов с аналогичными командами[]

В следующей таблице содержится выборка командлетов, поставляющихся с PowerShell, с приведением максимально похожих команд из других широко известных оболочек командной строки.

Следует отметить, что данная таблица приводится для поверхностного ознакомления, она не охватывает всех возможностей представленных оболочек.

Windows PowerShell
(Cmdlet)
Windows PowerShell
(Alias)
cmd.exe / COMMAND.COM
(MS-DOS, Windows, OS/2, etc.)
Bash
(Unix, BSD, Linux, Mac OS X и т. п.)
Описание
Get-Location gl, pwd cd[3] pwd Отображает текущий рабочий каталог
Set-Location sl, cd, chdir cd, chdir cd Меняет текущий каталог
Clear-Host cls, clear cls clear Очищает экран[4]
Copy-Item cpi, copy, cp copy cp Копирует один или несколько файлов или дерево директорий (в PowerShell также можно копировать объекты других поставщиков данных)
Get-Help help, man help man Справка по командам
Remove-Item ri, del, erase, rmdir, rd, rm del, erase, rmdir, rd rm, rmdir Удаляет файл/каталог (или другой элемент в поставщиках данных PowerShell).
Rename-Item rni, ren ren, rename mv Переименовывает файл/каталог
Move-Item mi, move, mv move mv Перемещает файл/каталог в новое местоположение
Get-ChildItem gci, dir, ls dir ls Выводит все файлы/каталоги в текущем каталоге
Write-Output echo, write echo echo Выводит строки, переменные на стандартный вывод
Pop-Location popd popd popd Изменяет текущий каталог на тот, который был последним помещён в стек
Push-Location pushd pushd pushd Помещает текущий каталог в стек
Set-Variable sv, set set set Установка значения переменной/создание переменной
Get-Content gc, type, cat type cat Получает содержимое файла
Select-String sls find, findstr grep Выводит строки, подходящие под условие
Get-Process gps, ps tlist,[5] tasklist[6] ps Выводит все запущенные процессы
Stop-Process spps, kill kill,[5] taskkill[6] kill Останавливает запущенный процесс
Tee-Object tee n/a tee Передаёт входные данные в файл или переменную, затем передаёт их дальше по конвейеру

См. также[]

  • Сравнение командных оболочек
  • PowerShell ISE

Примечания[]

  1. Описание Windows Management Framework
  2. Realtime Syntax Highlighting in PowerShell Console » PowerShell и другие скрипты
  3. cd без параметров выводит текущий каталог.
  4. Clear-Host реализован как предопределённая функция PowerShell.
  5. 5,0 5,1 Available in Windows NT4, Windows 98 Resource Kit, Windows 2000 Support Tools
  6. 6,0 6,1 Available in Windows XP Professional Edition and later

Литература[]

  • Шаблон:±. Введение в Windows PowerShell. — Шаблон:Указание места в библиоссылке: БХВ-Петербург, 2009. — С. 464. — ISBN 978-5-9775-0283-2.

Ссылки[]

  • Обучающие ресурсы по Windows PowerShell
  • Центр загрузки установочного пакета Windows PowerShell 1.0 для системы Windows Vista
  • Доклад о нововведениях в PowerShell 2.0
  • Доклад о регулярных выражениях в Windows PowerShell
  • Доклад о возможностях PowerShell и основах написания сценариев
  • Windows Management Framework (включающий PowerShell 2.0, WinRM 2.0 и BITS 4.0) для Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008
  • Блог «PowerShell и другие скрипты»Шаблон:Ref-ru
  • «Блог Бешкова Андрея из Microsoft, о Powershell»Шаблон:Ref-ru
  • Бесплатная русская книга о PowerShellШаблон:Ref-ru
  • Вторая бесплатная английская книга о PowerShellШаблон:Ref-en
  • Веб-узел Windows PowerShellШаблон:Ref-en
  • Капитан PowerShell и администрирование будущего Шаблон:Ref-ru
  • Могучий шелл
  • Виртуальная лаборатория «Creating Windows PowerShell Script Cmdlets»
  • PowerShell 2.0 RTM доступен для всех версий Windows

Шаблон:Rq
Шаблон:Microsoft APIs
Шаблон:DotNET
Шаблон:Windows API

 Просмотр этого шаблона Компоненты Microsoft Windows
Основные

Aero •
ClearType •
Диспетчер рабочего стола •
DirectX •
Панель задач
(Пуск •

Область уведомлений) •
Проводник
(Пространство имён •

Специальные папки
Ассоциации файлов) •
Windows Search
(Smart folders

iFilters) •
GDI •
WIM
SMB •
.NET Framework •
XPS •
Active Scripting
(WSH •

VBScript •
JScript) •
COM
(OLE •

DCOM •
ActiveX •
Структурированное хранилище
Сервер транзакций) •
Теневая копия
WDDM •
UAA
Консоль Win32

Службы
управления

Архивация и восстановление
COMMAND.COM •
cmd.exe •
Средство переноса данных •
Просмотр событий
Установщик •
netsh.exe
PowerShell
Отчёты о проблемах
rundll32.exe •
Программа подготовки системы (Sysprep) •
Настройка системы (MSConfig) •
Проверка системных файлов
Индекс производительности •
Центр обновления •
Восстановление системы •
Дефрагментация диска
Диспетчер задач •
Диспетчер устройств •
Консоль управления •
Очистка диска •
Панель управления
(элементы)

Приложения

Контакты •
DVD Maker
Факсы и сканирование
Internet Explorer •
Журнал
Экранная лупа •
Media Center •
Проигрыватель Windows Media •
Программа совместной работы
Центр устройств Windows Mobile
Центр мобильности •
Экранный диктор
Paint •
Редактор личных символов
Удалённый помощник
Распознавание речи
WordPad •
Блокнот •
Боковая панель •
Звукозапись
Календарь
Калькулятор
Ножницы
Почта •
Таблица символов •
Исторические:
Movie Maker •

NetMeeting •
Outlook Express •
Диспетчер программ •
Диспетчер файлов •
Фотоальбом •
Windows To Go

Игры

Chess Titans •
Mahjong Titans
Purble Place •
Пасьянсы (Косынка
Паук
Солитер) •
Сапёр
Пинбол •
Червы

Ядро ОС

Ntoskrnl.exe •
Слой аппаратных абстракций (hal.dll) •
Бездействие системы •
svchost.exe •
Реестр •
Службы •
Диспетчер управления сервисами
DLL
(формат модулей) •

PE •
NTLDR •
Диспетчер загрузки
Программа входа в систему (winlogon.exe) •
Консоль восстановления
Windows RE
Windows PE •
Защита ядра от изменений

Службы

Autorun.inf •
Фоновая интеллектуальная служба передачи
Файловая система стандартного журналирования
Отчёты об ошибках
Планировщик классов мультимедиа
Теневая копия
Планировщик задач •
Беспроводная настройка

Файловые
системы

ReFS •
NTFS
(Жёсткая ссылка

Точка соединения •
Точка монтирования
Точка повторной обработки
Символьная ссылка •
TxF •
EFS) •
WinFS •
FAT •
exFAT •
CDFS •
UDF
DFS •
IFS

Сервер

Active Directory •
Службы развёртывания •
Служба репликации файлов
DNS
Домены
Перенаправление папок
Hyper-V •
IIS •
Media Services
MSMQ
Защита доступа к сети (NAP) •
Службы печати для UNIX
Удалённое разностное сжатие
Службы удаленной установки
Служба управления правами
Перемещаемые профили пользователей •
SharePoint •
Диспетчер системных ресурсов
Удаленный рабочий стол
WSUS •
Групповая политика •
Координатор распределённых транзакций

Архитектура

NT •
Диспетчер объектов
Пакеты запроса ввода/вывода
Диспетчер транзакций ядра
Диспетчер логических дисков
Диспетчер учетных записей безопасности
Защита ресурсов
lsass.exe
csrss.exe •
smss.exe •
spoolsv.exe
Запуск

Безопасность

BitLocker
Защитник •
Предотвращение выполнения данных
Обязательный контроль целостности
Защищённый канал данных
UAC •
UIPI
Брандмауэр •
Центр обеспечения безопасности •
Защита файлов

Совместимость

Подсистема UNIX (Interix) •
Виртуальная машина DOS •
Windows on Windows •
WOW64

Как нет двух одинаковых операционных систем Windows, так и нет двух одинаковых версий оболочки Windows PowerShell. Шаги, которые нужно предпринять для запуска оболочки PowerShell 2.0 в системе Windows 8 (http://windowsitpro.com/windows-client/windows-8) заметно отличаются от действий, необходимых для запуска версии PowerShell 3.0 на сервере Windows Server 2008. При этом обилие документации по оболочке PowerShell может усложнить поиск точных сведений о том, что именно следует сделать для настройки определенной версии PowerShell в конкретной операционной системе

.

Я попытаюсь упростить информацию о системных требованиях, разделив ее в соответствии с используемой операционной системой. Точнее, я затрону те операционные системы, в которых могут быть запущены обе версии оболочки PowerShell (2.0 и 3.0): Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2 и Server 2008. Для каждой операционной системы я подробно расскажу о запуске обеих версий PowerShell, а также среды разработки PowerShell Integrated Scripting Environment (ISE). Иногда отличий между операционными системами с точки зрения запуска оболочки PowerShell будет немного, но даже в этих случаях я постараюсь четко их обозначить, чтобы вы ясно понимали, как развернуть оболочку PowerShell в своем окружении.

Windows 8

Если вы уже используете систему Windows 8, вам повезло. Ядро PowerShell 3.0 и среда ISE в ней установлены и активированы. Вы можете запустить любое из этих двух решений, как и любое другое приложение, из меню Start, с рабочего стола или из командной строки Windows. Оболочка PowerShell 3.0 готова к запуску и ждет только вашего решения использовать ее.

К сожалению, сказанное не распространяется на оболочку PowerShell 2.0. Хотя ядро PowerShell 2.0 является частью пакета, то есть установлено в системе Windows 8, необходимо сначала активировать компонент Microsoft. NET Framework 3.5. И на то есть причина. Так как ядро PowerShell 2.0 скомпилировано в среде Common Language Runtime (CLR) 2.0, ему требуется платформа. NET версии 3.5 или ниже (назад к. NET 2.0). Оболочке PowerShell 3.0 необходимы версии. NET 4.0 или. NET 4.5, каждая из которых построена на основе CLR 4.0. В системе Windows 8 компоненты. NET 4.5 установлены и активированы по умолчанию, и именно по этой причине вы можете задействовать оболочку PowerShell 3.0 без предварительной настройки.

Если вам необходима возможность использовать как версию PowerShell 3.0, так и версию PowerShell 2.0, вы должны сначала активировать компонент. NET Framework 3.5 (включает версии. NET 2.0 и 3.0) в окне Windows Features. Это шаг активирует платформу.NET 3.5 и позволяет запускать версию PowerShell 2.0 наравне с PowerShell 3.0. Однако вы не найдете пункт меню Start, запускающий оболочку PowerShell 2.0. Для запуска потребуется выполнить следующую команду из командной строки системы Windows или оболочки PowerShell:

powershell -version 2

После запуска этой команды все последующие команды, запущенные в рамках текущей сессии, будут обработаны ядром PowerShell 2.0. Однако имейте в виду, что оболочка PowerShell 3.0 обратно совместима с командами, провайдерами, сценариями, модулями и привязками из версии PowerShell 2.0. Поэтому единственный случай, когда вам может понадобиться использовать ядро PowerShell 2.0, это если вы хотите проверить совместимость сценария или основной программы, написанной специально для оболочки PowerShell 2.0 и среды CLR 2.0.

Также будьте готовы к тому, что вы не сможете запустить среду PowerShell 2.0 ISE, если установлена оболочка PowerShell 3.0. При таких условиях вам удастся запустить версию PowerShell 2.0 только из командной оболочки. Однако вы можете использовать среду PowerShell 3.0 ISE для создания сценария, и потом запустить созданный сценарий в оболочке PowerShell 2.0 для проверки совместимости. Может быть это и не оптимальное, но все же решение.

Windows Server 2012

Если говорить об оболочке PowerShell, то система Server 2012 во многом похожа на Windows 8. По умолчанию установлены, активированы и готовы к использованию ядро и среда ISE версии PowerShell 3.0. Вы можете запустить их из меню Start, с рабочего стола или из командной строки Windows. Кроме того, вы можете запустить оболочку PowerShell 3.0 из окна Server Manager.

Однако для работы оболочки PowerShell 2.0 требуется немного другой подход к подготовке системы, чем при работе с Windows 8. Для начала вы должны добавить компонент. NET 3.5, а не просто включить его. Для этого используйте функцию Add roles and Features в окне диспетчера сервера, чтобы добавить в систему компонент. NET Framework 3.5 (включающий версии 2.0 и 3.0). Чтобы получить доступ к этому компоненту, выберите тип установки Role based или Feature based, когда попадете на страницу выбора типа установки.

Следующий шаг в подготовке к PowerShell 2.0 — это добавление актуального ядра. Снова используйте функцию Add Roles and Features в окне Server Manager, выберите тип установки Role-based или Feature-based и компонент Windows PowerShell 2.0 Engine.

После того как вы добавили возможности пакета. NET 3.5 и ядра PowerShell 2.0, вы сможете запустить ядро PowerShell 2.0. Для этого введите следующую команду в командной строке Windows или PowerShell:

powershell -version 2

Windows 7

В отличие от систем Windows 8 и Server 2012, в состав системы Windows 7 не входят предустановленные ядро PowerShell 3.0 Engine и среда ISE. Наоборот, в состав Windows 7 входят установленные, активированные и готовые к запуску ядро PowerShell и редактор ISE версии 2.0.

Имейте в виду, что если вы щелкаете правой кнопкой мыши на значке PowerShell в меню Start и выбираете пункт Properties, то в строке Target может быть прописана версия v1.0, как показано на приведенном экране. Однако при этом оболочка PowerShell остается работоспособной и вы можете проверить данное утверждение, открыв окно PowerShell и запустив команду Get-Host.

Свойства PowerShell
Экран. Свойства PowerShell

Вы можете запустить оболочку PowerShell или редактор ISE из меню Start или командной строки. Чтобы запустить оболочку PowerShell 2.0 с помощью командной строки, введите команду:

powershell

Чтобы запустить редактор PowerShell 2.0 ISE из командной строки, введите команду:

powershell_ise

Система Windows 7 поддерживает использование версии PowerShell 3.0, но для ее запуска вам нужно будет выполнить несколько шагов.

  1. Установите пакет обновления Windows 7 SP1 (http://www.microsoft.com/en-us/download/details.aspx?id=5842), если еще не сделали этого.
  2. Выполните полную установку компонентов. NET 4.0 (http://www.microsoft.com/en-us/download/details.aspx?id=17851) или. NET 4.5(http://www.microsoft.com/en-us/download/details.aspx?id=30653).
  3. Удалите все предыдущие сборки Windows Management Framework (WMF) 3.0.
  4. Установите последнюю сборку WMF 3.0 (http://www.microsoft.com/en-us/download/details.aspx?id=34595).

Вдобавок к ядру PowerShell 3.0 и среде ISE пакет WMF 3.0 включает и другие компоненты, необходимые для запуска оболочки PowerShell 3.0.

  • WS-Management 3.0. Этот компонент поддерживает работу службы Windows Remote Management (WinRM) и протокола WSMan, которые делают возможным использование компонентов PowerShell, связанных с дистанционным управлением.
  • Windows Management Instrumentation (WMI) 3.0. Этот компонент поддерживает функции, которым необходим инструментарий WMI, например команды Common Information Model (CIM).

Установка пакетов. NET и WMF представляет собой интуитивно понятные процессы, но убедитесь, что вы прочитали все инструкции на странице загрузки, перед тем как установить пакеты в своей системе. Еще одна важная деталь заключается в том, что пакет WMF несовместим с некоторыми приложениями:

  • Microsoft System Center 2012 Configuration Manager;
  • Microsoft System Center 2012 Virtual Machine Manager;
  • Microsoft Exchange Server 2012;
  • Microsoft Exchange Server 2007;
  • Microsoft SharePoint 2010;
  • Windows Small Business Server 2011;
  • Windows Small Business Server 2008.

Если в вашей системе были установлены приложения из приведенного списка, вам не следует устанавливать пакет WMF 3.0, а следовательно обновление до версии PowerShell 3.0 становится невыполнимой задачей (если только вы не найдете обходной путь).

Однако если рассматривать вариант, в котором вы сможете выполнить установку пакета WMF 3.0, то оболочка PowerShell 3.0 и среда ISE будут готовы к запуску, как только закончится установка. В системе Windows 7 запуск ядра PowerShell выполняется точно так же как запуск оболочки PowerShell и редактора ISE версии 2.0 (то есть из меню Start или из командной строки). Если вы хотите запустить ядро оболочки PowerShell 2.0, введите в командную строку следующую команду:

powershell -version 2

Однако имейте в виду, что после установки пакета WMF 3.0 вы сможете получить доступ к ядру оболочки PowerShell 2.0 только через эту команду. Кроме того, вы больше не сможете использовать редактор PowerShell ISE и запускать ядро PowerShell 2.0 из оболочки PowerShell 3.0. Вам придется задействовать командную оболочку PowerShell, чтобы выполнять операции версии 2.0. Однако, как и при работе с системами Windows 8 и Server 2012, вы сможете использовать редактор PowerShell 3.0 ISE, чтобы создавать свои сценарии и запускать их на ядре PowerShell 2.0 для проверки совместимости.

Windows Server 2008 R2

Система Server 2008 R2 очень похожа на Windows 7 с точки зрения настройки PowerShell. По умолчанию ядро PowerShell 2.0 и редактор ISE установлены в системе. Однако, в отличие от системы Windows 7, на платформе Server 2008 R2 активировано ядро, но не среда ISE. Вам придется установить ее вручную при помощи функции Add Features в окне Server Manager, позволяющей добавить компонент Windows PowerShell Integrated Scripting Environment (ISE). Как только этот компонент будет добавлен, вы сможете запускать и оболочку PowerShell 2.0, и ISE, точно так же, как в системе Windows 7 (с помощью меню Start или командной строки).

Процесс обновления оболочки PowerShell 2.0 до версии Powershell 3.0 похож на процесс обновления в системе Windows 7. Вы устанавливаете пакет обновления SP1, загружаете компоненты. NET 4.0 или. NET 4.5, удаляете все предыдущие сборки WMF 3.0 и устанавливаете самую последнюю сборку WMF 3.0, соблюдая все предосторожности, описанные в разделе, посвященном системе Windows 7. Однако если вы хотите использовать редактор РоwerShell 3.0 ISE после обновления, вы должны быть уверены, что редактор PowerShell 2.0 ISE был активирован до установки пакета WMF 3.0.

После установки пакета WMF 3.0 вы сможете запустить ядро PowerShell 3.0 и редактор ISE, точно так же, как вы запускали их в системе Windows 7 (то есть с помощью меню Start или командной строки). Чтобы получить доступ к ядру PowerShell 2.0, нужно ввести следующую команду в командной строке системы Windows или оболочки PowerShell:

powershell -version 2

Windows Server 2008

Когда дело дойдет до настройки PowerShell, вы увидите, что платформа Windows Server 2008 действительно отличается от других систем. Эта операционная система не включает в себя предустановленных компонентов PowerShell 2.0 или PowerShell 3.0. В результате вам придется проделать больше работы, чтобы запустить какую-либо из этих версий в своей системе.

Если вы хотите установить ядро PowerShell 2.0 и редактор ISE на компьютер с системой Server 2008, сначала придется удалить все предыдущие версии служб PowerShell или WinRM. Затем, вам нужно установить пакет WMF Core (http://support.microsoft.com/kb/968929/en-us), включающий в себя ядро PowerShell 2.0, среду ISE, а также пакет WinRM 2.0. Теперь вы сможете запускать компоненты PowerShell точно так же, как вы запускали их в системах Windows 7 или Server 2008 R2.

Процесс установки ядра PowerShell 3.0 и ISE не так прост и требует дополнительных шагов.

  • Установите пакет обновления Server 2008 SP2 (http://www.microsoft.com/en-us/download/details.aspx?id=16468), если он еще не был установлен.
  • Установите пакет WMF Core (http://support.microsoft.com/kb/968929/en-us), если он еще не был установлен. Наличие компонента WMF Core — это предварительное условие для установки пакета WMF 3.0 на компьютерах с системой Server 2008.
  • Полностью установите компоненты. NET 4.0 (http://www.microsoft.com/en-us/download/details.aspx?id=17851) или. NET 4.5 (http://www.microsoft.com/en-us/download/details.aspx?id=30653).
  • Установите компонент Extended Protection for Authentication (http://support.microsoft.com/kb/968389). Этот компонент защищает вашу систему от возможных атак и позволяет использовать параметр UseSSL при создании удаленной сессии.
  • Удалите все предыдущие сборки WMF 3.0.
  • Установите самую последнюю сборку WMF 3.0 (http://www.microsoft.com/en-us/download/details.aspx?id=34595).

После завершения процесса установки вы можете обратиться к ядру PowerShell и редактору ISE, как при запуске в системах Windows 7 или Server 2008 R2 (то есть из меню Start или командной строки). Вы можете получить доступ к ядру PowerShell 2.0 так же, как и в других системах, с помощью следующей команды в командной строке системы Windows или оболочки PowerShell:

powershell -version 2

Игра в PowerShell

Установка PowerShell может быть похожа на игру «в наперстки» — вам нужно угадать, где спрятан шарик. Если вы точно знаете, какую версию PowerShell и в какой операционной системе хотите использовать, весь вопрос заключается лишь в выборе правильного набора инструкций.

Помните, что вы можете запустить ядро PowerShell 3.0 и среду ISE в любой из перечисленных здесь операционных систем. С версией PowerShell 3.0 вы не только получаете несколько важных новых команд, но и такие компоненты как Windows PowerShell Web Access, интеграцию с моделью Common Information Model (CIM), отключенные сессии и поддержку для Windows Workflow Foundation. Редактор PowerShell 3.0 ISE был значительно расширен с добавлением поддержки таких технологий как IntelliSense, автоматическое сохранение, копирование блока, сопоставление с эталоном и раскрывающиеся-закрывающиеся разделы. И самое главное, что вы по-прежнему можете получить доступ к ядру PowerShell 2.0.

Даже если вы решили работать только с версией PowerShell 2.0, вы все равно должны убедиться в том, что работаете с правильной версией PowerShell и что она запускается в нужной вам системе. В связи с этим у вас должна быть вся необходимая информация для настройки окружения PowerShell 2.0.

Аннотация: Описываются возможности оболочки Windows PowerShell и отличие ее от традиционных оболочек и языков сценариев. Обсуждаются основные концепции PowerShell (типы команд, структура командлетов, псевдонимы команд). Рассматриваются особенности справочной системы PowerShell

Введение в оболочку командной строки Windows PowerShell

На настоящий момент мы рассмотрели уже три разных инструмента, предназначенных для автоматизации работы в операционной системе Windows: оболочки командной строки Cmd.exe и WMIC, а также сервер сценариев WSH. Зачем же компании Microsoft понадобилась разработка еще одной полностью новой оболочки командной строки со своим языком сценариев?

Причины и цели создания новой оболочки

Чтобы ответить на этот вопрос, вспомним основные требования к «идеальному» средству автоматизации, которые мы обсуждали в первой лекции, и посмотрим, в какой степени удовлетворяют этим требованиям перечисленные выше инструменты (табл.16.1).

Таблица
16.1.
Требования к инструменту автоматизации

Требование Cmd.exe WSH WMIC
Работа во всех версиях операционной системы без установки дополнительного программного обеспечения Да Да Нет (только Windows XP и выше)
Интеграция с командной строкой Да Нет Да
Согласованный и непротиворечивый синтаксис команд и утилит Нет Нет Да
Поддержка псевдонимов (кратких синонимов) для длинных названий команд Нет Нет Да
Автоматическое завершения команд и имен файлов при вводе их с клавиатуры Частично (автоматическое завершение имен файлов и папок) Нет Нет
Поддержка истории введенных команд с возможностью их повторного вызова, просмотра и редактирования Да Нет Да
Наличие подробной встроенной справки по командам с примерами использования Частично Нет Да
Возможность автоматического выполнения сценариев Да (язык командных файлов) Да (языки сценариев VBScript, JScript и т.д.) Частично (команды WMIC можно встраивать в командные файлы)
Доступ и использование всех технологий и возможностей, поддерживаемых операционной системой Нет (нет прямого доступа к объектам COM, WMI, ADSI, .NET) Да Нет (доступ только к объектам WMI)

Как мы видим, у каждого из рассмотренных нами ранее инструментов автоматизации присутствовали довольно серьезные недостатки, не позволявшие сказать, что Windows обладает по-настоящему мощным и эффективным средством для работы с командной строкой и написания сценариев.

Новая оболочка Windows PowerShell (предварительно она была названа Monad) была задумана разработчиками Microsoft как более мощная среда для написания сценариев и работы из командной строки. Разработчики PowerShell преследовали несколько целей. Главная и самая амбициозная из них – создать среду составления сценариев, которая наилучшим образом подходила бы для современных версий операционной системы Windows и была бы более функциональной, расширяемой и простой в использовании, чем какой-либо аналогичный продукт для любой другой операционной системы. В первую очередь эта среда должна была подходить для решения задач, стоящих перед системными администраторами (тем самым Windows получила бы дополнительное преимущество в борьбе за сектор корпоративных платформ), а также удовлетворять требованиям разработчиков программного обеспечения, предоставляя им средства для быстрой реализации интерфейсов управления к создаваемым приложениям.

Для достижения этих целей были решены следующие задачи:

  • Обеспечение прямого доступа из командной строки к объектам COM, WMI и .NET. В новой оболочке присутствуют команды, позволяющие в интерактивном режиме работать с COM-объектами, а также с экземплярами классов, определенных в информационных схемах WMI и .NET.
  • Организация работы с произвольными источниками данных в командной строке по принципу файловой системы. Например, навигация по системному реестру или хранилищу цифровых сертификатов выполняется из командной строки с помощью аналога команды CD интерпретатора Cmd.exe.
  • Разработка интуитивно понятной унифицированной структуры встроенных команд, основанной на их функциональном назначении. В новой оболочке имена всех внутренних команд (в PowerShell они называются командлетами) соответствуют шаблону «глагол-существительное», например, Get-Process (получить информацию о процессе), Stop-Service (остановить службу), Clear-Host (очистить экран консоли) и т.д. Для одинаковых параметров внутренних команд используются стандартные имена, структура параметров во всех командах идентична, все команды обрабатываются одним синтаксическим анализатором. В результате облегчается запоминание и изучение команд.
  • Обеспечение возможности расширения встроенного набора команд. Внутренние команды PowerShell могут дополняться командами, создаваемыми пользователем. При этом они полностью интегрируются в оболочку, информация о них может быть получена из стандартной справочной системы PowerShell.
  • Организация поддержки знакомых команд из других оболочек. В PowerShell на уровне псевдонимов собственных внутренних команд поддерживаются наиболее часто используемые стандартные команды из оболочки Cmd.exe и Unix-оболочек. Например, если пользователь, привыкший работать с Unix-оболочкой, выполнит ls, то он получит ожидаемый результат: список файлов в текущем каталоге (то же самое относится к команде dir).
  • Разработка полноценной встроенной справочной системы для внутренних команд. Для большинства внутренних команд в справочной системе дано подробное описание и примеры использования. В любом случае встроенная справка по любой внутренней команде будет содержать краткое описание всех ее параметров.
  • Реализация автоматического завершения при вводе с клавиатуры имен команд, их параметров, а также имен файлов и папок. Данная возможность значительно упрощает и ускоряет ввод команд с клавиатуры.

Главной особенностью среды PowerShell, отличающей ее от всех других оболочек командной строки, является то, что единицей обработки и передачи информации здесь является объект, а не строка текста.

Отличие PowerShell от других оболочек – ориентация на объекты

При разработке любого языка программирования одним из основных является вопрос о том, какие типы данных и каким образом будут в нем представлены. При создании PowerShell разработчики решили не изобретать ничего нового и воспользоваться унифицированной объектной моделью .NET. Данный выбор был сделан по нескольким причинам.

Во-первых, платформа .NET повсеместно используется при разработке программного обеспечения для Windows и представляет, в частности, общую информационную схему, с помощью которой разные компоненты операционной системы могут обмениваться данными друг с другом.

Во-вторых, объектная модель .NET является самодокументируемой: каждый объект .NET содержит информацию о своей структуре. При интерактивной работе это очень полезно, так как появляется возможность непосредственно из командной строки выполнить запрос к определенному объекту и увидеть описание его свойств и методов, то есть понять, какие именно манипуляции можно проделать с данным объектом, не изучая дополнительной документации с его описанием.

В-третьих, работая в оболочке с объектами, можно с помощью их свойств и методов легко получать нужные данные, не занимаясь разбором и анализом символьной информации, как это происходит во всех традиционных тексто-ориентированных оболочках командной строки. Рассмотрим пример. В Windows XP есть консольная утилита tasklist.exe, которая выдает информацию о процессах запущенных в системе:

C:>tasklist

Имя образа                   PID Имя сессии       № сеанса       Память
========================= ====== ================ ======== ============
System Idle Process            0                         0        16 КБ
System                         4                         0        32 КБ
smss.exe                     560                         0        68 КБ
csrss.exe                    628                         0     4 336 КБ
winlogon.exe                 652                         0     3 780 КБ
services.exe                 696                         0     1 380 КБ
lsass.exe                    708                         0     1 696 КБ
svchost.exe                  876                         0     1 164 КБ
svchost.exe                  944                         0     1 260 КБ
svchost.exe                 1040                         0    10 144 КБ
svchost.exe                 1076                         0       744 КБ
svchost.exe                 1204                         0       800 КБ
spoolsv.exe                 1296                         0     1 996 КБ
kavsvc.exe                  1516                         0     9 952 КБ
klnagent.exe                1660                         0     5 304 КБ
klswd.exe                   1684                         0        64 КБ

Предположим, что мы в командном файле интерпретатора Cmd.exe с помощью этой утилиты хотим определить, сколько оперативной памяти тратит процесс kavsvc.exe. Для этого нужно выделить из выходного потока команды tasklist соответствующую строку, извлечь из нее подстроку, содержащую нужное число и убрать пробелы между разрядами (при этом следует учесть, что в зависимости от настроек операционной системы разделителем разрядов может быть не пробел, а другой символ). В PowerShell аналогичная задача решается с помощью команды get-process, которая возвращает коллекцию объектов, каждый из которых соответствует одному запущенному процессу. Для определения памяти, затрачиваемой процессом kavsvc.exe, нет необходимости в дополнительных манипуляциях с текстом, достаточно просто взять значение свойства WS объекта, соответствующего данному процессу.

Наконец, объектная модель .NET позволяет PowerShell напрямую использовать функциональность различных библиотек, являющихся частью платформы .NET. Например, чтобы узнать, каким днем недели было 9 ноября 1974 года, в PowerShell можно выполнить следующую команду:

(get-date "09.11.1974").DayOfWeek

В этом случае команда get-date возвращает .NET-объект DateTime, имеющий свойство, при обращении к которому вычисляется день недели для соответствующей даты. Таким образом, разработчикам PowerShell не нужно создавать специальную библиотеку для работы с датами и временем – они просто берут готовое решение в .NET.

Загрузка и установка PowerShell

Оболочка PowerShell может работать не во всех версиях операционной системы, ее можно использовать в Windows XP SP 2, Windows Server 2003 SP 1 и более поздних версиях. Кроме этого, в системе должна быть установлена платформа .NET Framework 2.0 (в Windows XP данную среду придется устанавливать дополнительно, дистрибутив можно загрузить с сайта Microsoft по адресу http://msdn.microsoft.com/netframework/downloads/updates/default.aspx).

Загрузить PowerShell можно с сайта Microsoft, открыв страницу http://microsoft.com/powershell, где имеются ссылки на файл установки последней версии и пакеты документации на разных языках. Запустив загруженный файл, следуйте указаниям мастера установки. В 32-разрядных версиях Windows оболочка PowerShell устанавливается по умолчанию в каталог %SystemRoot%System32WindowsPowerShellv1.0. В 64-разрядных версиях Windows 32-разрядная версия PowerShell устанавливается в каталог %SystemRoot%SystemWow64WindowsPowerShellv1.0, а 64-разрядная версия Windows PowerShell устанавливается в каталог %SystemRoot%System32WindowsPowerShellv1.0.

Запуск оболочки. Выполнение команд

Установив оболочку в системе, можно начать новый интерактивный сеанс. Для этого следует нажать на кнопку Пуск (Start), открыть меню Все программы (All Programs) и выбрать элемент Windows PowerShell. Другой вариант запуска оболочки – пункт Выполнить… (Run) в меню Пуск (Start), ввести имя файла powershell и нажать кнопку OK.

В результате откроется новое командное окно с приглашением вводить команды (рис. 16.1).

Выполним первую команду в PowerShell. Пусть это будет что-то знакомое, например dir (команды в PowerShell обрабатываются без учета регистра). На экран будет выведен список файлов в текущем каталоге:

PS C:Documents and SettingsUser> dir
    Каталог: Microsoft.PowerShell.CoreFileSystem::C:Documents 
      and SettingsUser
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d---s        14.12.2007     10:10            Cookies
d----        12.05.2005     17:16            DoctorWeb
d----        06.11.2004     13:03            Phone Browser
d---s        22.09.2004     23:49            UserData
d-r--        04.10.2004     15:33            Главное меню
d-r--        05.12.2007      0:49            Избранное
d-r--        31.10.2007     21:03            Мои документы
d----        05.12.2007     10:54            Рабочий стол
-a---        24.05.2006     21:22       8304 gsview32.ini

Типы команд PowerShell

В оболочке PowerShell поддерживаются команды четырех типов: командлеты, функции, сценарии и внешние исполняемые файлы.

Первый тип – так называемые командлеты (cmdlet). Этот термин используется пока только внутри PowerShell. Командлет представляет собой класс .NET, порожденный от базового класса Cmdlet ; разрабатываются командлеты с помощью пакета PowerShell Software Developers Kit (SDK). Единый базовый класс Cmdlet гарантирует совместимый синтаксис всех командлетов, а также автоматизирует анализ параметров командной строки и описание синтаксиса командлетов для встроенной справки.

Данный тип команд компилируется в динамическую библиотеку (DLL) и подгружается к процессу PowerShell во время запуска оболочки (то есть сами по себе командлеты не могут быть запущены как приложения, но в них содержатся исполняемые объекты). Так как компилированный код подгружается к процессу оболочки, данный тип команд выполняется наиболее эффективно. Командлеты – это аналог внутренних команд традиционных оболочек.

Следующий тип команд – функции. Функция – это блок кода на языке PowerShell, имеющий название и находящийся в памяти до завершения текущего сеанса командной оболочки. Функции, как и командлеты, поддерживают именованные параметры. Анализ синтаксиса функции производится один раз при ее объявлении.

Сценарий – это блок кода на языке PowerShell, хранящийся во внешнем файле с расширением ps1. Анализ синтаксиса сценария производится при каждом его запуске.

Последний тип команд – внешние исполняемые файлы, которые выполняются обычным образом операционной системой.

I just installed XP SP2 and I was expecting to have PowerShell 1.0 installed; however, it isn’t.

It seems I have to manually install it. If I upgrade to SP3 do I get PowerShell.

From Wikipedia article:


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

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.


It seems PowerShell 1.0 or 2.0 doesn’t get installed by default in XP SP3, 2003 and Vista.

I can’t find any concrete information can someone confirm this please.

Dave M's user avatar

Dave M

4,51422 gold badges31 silver badges30 bronze badges

asked Jul 24, 2014 at 18:06

user1088352's user avatar

4

Windows 7/Server 2008 R2 are the first Windows versions to come with PowerShell installed, by default.

Windows PowerShell 2.0 needs to be installed on Windows Server 2008 and Windows Vista only. It is already installed on Windows Server 2008 R2 and Windows 7.

Ignoring the horribleness of installing XP SP2 in this day and age, if not having PowerShell installed by default is a problem, you have many options to correct that, both retroactively (like GPOs or startup/logon scripts to install it) and going forward (by slipstreaming it into an ISO image or a machine that you deploy).

answered Jul 24, 2014 at 18:49

HopelessN00b's user avatar

HopelessN00bHopelessN00b

53.8k33 gold badges137 silver badges210 bronze badges

1

Short answer

As already given: Windows XP doesn’t come with PowerShell integrated, so your specific solution is to install PS1 on WinXP SP2 assuming the availability of the software.

Long answer

Reading the dedicated section PowerShell #Version on Wikipedia gave me the following information. I stripped details and most of the (reliable and informative) for this overview:

Windows PowerShell Versions

Version integrated with released for
1.0 Windows XP SP2
Server 2003 SP1
Windows Vista
2.0 Windows 7
Windows Server 2008 R2[59]
Windows XP SP3
Windows Server 2003 SP2
Windows Vista SP1
3.0 Windows 8
Windows Server 2012
Windows 7 SP1
Windows Server 2008 SP1
Windows Server 2008 R2 SP1
4.0 Windows 8.1
Windows Server 2012 R2
Windows 7 SP1
Windows Server 2008 R2 SP1
Windows Server 2012
5.1 Windows 10 Anniversary Update
Windows Server 2016
Windows 7
Windows Server 2008
Windows Server 2008 R2
Windows Server 2012
Windows Server 2012 R2

PowerShell Core 6

PowerShell Core 6 is the first free, cross-plattform implementation of PoweShell (Note the missing Windows and the additional Core in the name)

  • PowerShell is Microsoft’s latest open source release, coming to Linux, OS X | Ars Technica
  • PowerShell Core 6.0: Generally Available (GA) and Supported! | PowerShell Team

PowerShell 7

PowerShell 7 replaces PowerShell Core 6.x products and Windows PowerShell 5.1 with focus on becoming a viable replacement for PS 5.1. The Core part in the name was removed to reflect the join.

  • PowerShell 7 Roadmap | PowerShell Team

answered Jun 3, 2021 at 11:16

Wolf's user avatar

WolfWolf

1831 silver badge8 bronze badges

PowerShell is not installed with Windows XP. You have to manually install it afterwards.

answered Jul 24, 2014 at 18:14

pauska's user avatar

pauskapauska

19.6k5 gold badges57 silver badges75 bronze badges

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

  • Какие алгоритмы распределения памяти использует современная ос windows а какие ос linux
  • Какая файловая система должна быть на загрузочной флешки windows 10
  • Какие автозагрузки можно отключить в windows 10
  • Какая у меня версия операционной системы windows
  • Какие версии операционной системы windows были выпущены фирмой microsoft