Definition

PowerShell

PowerShell is an object-oriented automation engine and scripting language with an interactive command-line shell that Microsoft developed to help IT professionals configure systems and automate administrative tasks.

PowerShell, built on the .NET framework, works with objects, whereas most command-line shells are based on text. PowerShell serves as an automation tool for system administrators, employed in both IT departments and external entities, such as managed service providers, because of its scripting capabilities.

Content Continues Below

PowerShell originated as a propriety offering that was only available on Windows. In 2016, Microsoft open sourced PowerShell and made it available on Linux and macOS.

What does PowerShell do?

Microsoft designed PowerShell to automate system tasks, such as batch processing, and to create system management tools for commonly implemented processes. The PowerShell language, similar to Perl, offers several ways to automate tasks:

  • with cmdlets, which are very small .NET classes that appear as system commands;
  • with scripts, which are combinations of cmdlets and associated logic;
  • with executables, which are stand-alone tools; and
  • with the instantiation of standard .NET classes.

Admins can use PowerShell to handle a wide range of activities. It can extract information on OSes, such as the specific version and service pack levels. "PowerShell providers" are programs that make data contained in specialized data stores accessible at the command line. Those data stores include file system drives and Windows registries.

PowerShell also serves as the replacement for Microsoft's Command Prompt, which dates back to DOS. Microsoft, for example, made PowerShell the default command-line interface (CLI) for Windows 10 as of build 14791. PowerShell's role as a command-line shell is how most users become acquainted with the technology.

Key PowerShell features

Microsoft incorporates updates and new features with each PowerShell version, but here is a list of the primary features and characteristics.

Discoverability. Users can discover PowerShell's features using cmdlets such as Get-Command, which creates a list of all the commands, including cmdlets and functions, available on a given computer. Parameters can be used to narrow the scope of the search.

Help capabilities. Users can learn more about PowerShell principles and particular components such as cmdlets through the Get-Help cmdlet. The -online parameter provides access to help articles on the web, if available for a particular topic.

Remote commands. Admins can perform remote operations on one or multiple computers, taking advantage of technologies such as Windows Management Instrumentation and WS-Management. The WS-Management protocol, for example, lets users run PowerShell commands and scripts on remote computers.

Pipelining. With PowerShell, commands can be linked together through the pipe operator, symbolized as |. This approach lets the output from a given command become the input for the next command in the pipeline sequence. The PowerShell pipeline lets objects, rather than text strings, flow from one cmdlet to another.

Details on additional features can be found in the following sections.

Desired State Configuration

With PowerShell 4.0, Microsoft introduced a configuration management platform called Desired State Configuration (DSC), which admins can use to set a specific configuration for a server. After the admin defines the server settings, PowerShell ensures the target nodes retain that desired state. DSC has two modes of operation: push mode and pull mode.

In push mode, a server sends notifications to the nodes. It's a one-way communication, where the admin sends notifications from a workstation. Setup costs are less because management runs from a device, but a notification gets lost if the device isn't connected to the network.

In push mode, the IT department creates a pull server with the configuration details of each node using an MOF file. Each node contacts the pull server to check for a new configuration. If the new configuration is available, the pull server sends the configuration to the node. Admins can manage all devices regardless of their network connection. When a device connects to the network, it automatically contacts the pull server to check for a new configuration.

DSC resources

DSC resources are the components of a configuration script. Admins can check the available DSC resources on a machine with the Get-DscResource command.

PowerShell DSC
The Get-DscResource command retrieves the available Desired State Resources on a machine.

Admins use these resources to configure components such as registry keys and Windows services or to create and manage local users through a configuration script. For instance, the File resource manages files and folders, the Environment resource manages environment variables and the Registry resource manages the registry keys of a node.

PowerShell Integrated Scripting Environment

PowerShell Integrated Scripting Environment (ISE), introduced by Microsoft in PowerShell version 2.0, is a PowerShell host application used to write, test and debug scripts or write commands in a Windows graphical user interface (GUI).

PowerShell ISE comes with multiple features, such as syntax coloring, multiline editing, context-sensitive help and tab completion.

PowerShell ISE
Microsoft introduced the PowerShell Integrated Scripting Environment with PowerShell version 2.0.

PowerShell ISE has sophisticated features that are familiar to Windows users. For instance, a user can highlight and copy a portion of a PowerShell command with a mouse or with the Shift + Arrow hotkey combination. The user can also paste the content anywhere in the editor window.

Another useful feature is the ability to keep different versions of a command in the editor and run commands you need in the PowerShell ISE.

The F5 key launches a command directly from the editor. To execute a particular line, select it and press F8. The context-sensitive help displays matching cmdlets when the user starts to enter a command. A command add-on shows a list of cmdlets to select.

PowerShell ISE provides tabs to enable work on multiple administrative tasks. PowerShell ISE enables quick switching from the CLI to scripting mode.

PowerShell modules

PowerShell modules enable admins to reuse a script to automate a task. A PowerShell module can be defined as a set of PowerShell functions that are grouped to manage all the aspects of a particular area. PowerShell modules enable admins to reference, load, persist and share code. The simplest way to create a PowerShell module is to save the script as a PSM1 file.

A PowerShell module contains four essential elements:

  • a PSM file, which is the module;
  • help files or scripts needed by the module;
  • a manifest file that describes the module; and
  • a directory that stores the content.

A PowerShell module can be one of four types:

  • Script module: A PSM1 file that contains various functions to enable admins to perform import, export and management functions.
  • Binary module: A .NET framework assembly (DLL file) that contains compiled code. Developers typically use a binary module to create cmdlets with powerful features not easily done with a PowerShell script.
  • Manifest module: A manifest module is a module (PSM1) file with an associated PSD1 file (manifest).
  • Dynamic module: A dynamic module is created dynamically on demand by a script. It isn't stored or loaded to persistent storage.

PowerShell functions

A PowerShell function is similar to a PowerShell cmdlet, with several slight differences. Cmdlets are written in a compiled .NET language, such as C#, while functions are written in PowerShell and aren't compiled.

For developers and independent software vendors, it's easier to package and deploy a PowerShell cmdlet compared to packaging libraries of functions. Cmdlets and advanced functions support powerful parameter bindings.

By describing a parameter to the shell, admins can use any type of PowerShell parameters, such as named parameters, mandatory parameters and positional PowerShell parameters.

An example of a PowerShell function is:

function Set-Something {
  [CmdletBinding()]
  param (
    [Parameter()]
    [string]$Thing
  )

  Write-Host $Thing
}

A function contains one or more option parameters inside of a parameter block and a body.

Language constructs

As a scripting language, PowerShell offers several language constructs that control the flow of scripts, while making decisions as to what should be done. Some of the language constructs include conditionals, switches, loops and variables.

Conditionals. The language construct if is used to evaluate a conditional expression. When the conditional expression is true, a script block is executed.

if ($i -eq 1)
{
  ## Do something
}
else
{
  ## Do something else
}

Switch. The switch statement is used when there is a long list of conditional statements to test. Switch is commonly used in place of many if/then/else constructs.

switch ($i) {
  0
  {
    Write-Host "I is 0"
  }
  1
  {
    Write-Host "I is 0"
  }
  Default
  {
    Write-Host "I is not 0 or 1"
  }
}

Loops. The while statement repeats code as long as the following conditional expression is true:

while ($i -eq 0) {
  ## Do somthing
}

The do loop is similar to the while loop. The only difference is PowerShell executes the do loop at the end of the loop.

do {
  ## do something
} while ($i -lt 0)

When you use a foreach loop, PowerShell repeats the code for each item mentioned in the script.

$array = ('item1','item2','item3')
foreach ($item in $array) {
  $item
}

Use a for loop to execute statements repeatedly until a condition is met.

for ($i = 0; $i -lt 5; $i++)
{
  $i
}

Variables

Variables store data, but PowerShell variables are more powerful because they can be mapped to underlying classes in the .NET framework. PowerShell treats variables as .NET objects, which means they can store data and manipulate data in multiple ways.

Variable names in PowerShell start with a dollar sign and contain a mix of numbers, letters, symbols and spaces. For instance, $var="HELLO" stores the string HELLO in the $var variable. Variables can also have different scopes, such as global, local, script, private and numbered scopes.

Arrays

A PowerShell array is a component that enables the storage of more than one item in a variable or a field. For instance, to assign multiple values to a variable, use the following script:

$a=1,2,3

PowerShell treats each item in an array as a separate element. To address each item in an array, PowerShell offers index numbers. The first element in the array is indexed as 0 by default. The biggest advantage of PowerShell is that it automatically handles array insertions, so arrays don't have to be manually destroyed or created when adding or removing elements.

Hash tables

Hash tables are data structures similar to arrays. A PowerShell array stores multiple single items, but with a hash table, each item or value is stored using a key or value pair. An array can't store multiple values under each element, while a hash table can.

Below is an example comparing an array with a hash table:

$array = @('Joe','Susie','Donnie')
$hashtable = @{FirstName = 'Joe'; FirstName = 'Susie'; FirstName = 'Donnie'}

Help and comments

PowerShell enables the addition of help topics for modules, scripts and individual commands. To view all the help topics, use the Get-Help command.

When importing a module into a session, PowerShell automatically imports the help topics for that module. If there are no help topics for a module, the Get-Help command displays autogenerated help. Three types of help content exist in PowerShell: comment-based help, external help and updatable help.

Comment-based help refers to comments included with a script or command for Get-Help to read. External help enables the author to define help content in an external XML file written in XAML. Updatable help uses external help but enables users to download the latest help content with the Update-Help command.

Executable programs

PowerShell is also a cmd.exe replacement that runs an executable program in multiple ways through the Start-Process command, the ampersand and the Invoke-Expression command. Using ping.exe as an example, here's how a user can run the executable program using PowerShell:

Start-Process -FilePath 'ping.exe' -ArgumentList 'google.com' -Wait -NoNewWindow
& 'ping.exe' google.com
ping google.com
Invoke-Expression -Command 'ping.exe google.com'
This was last updated in March 2020

Continue Reading About PowerShell

Dig Deeper on Windows administration tools

Join the conversation

2 comments

Send me notifications when other members comment.

Please create a username to comment.

Where have you found the most benefit to using PowerShell in your environment?
Cancel
Huh?
Cancel

File Extensions and File Formats

SearchServerVirtualization

SearchCloudComputing

SearchSQLServer

SearchEnterpriseDesktop

SearchVirtualDesktop

Close