I write this as PowerShell approaches its 10th birthday since its release. PowerShell has come a long way since that time.
For me, PowerShell has gone from being a speculative replacement for a mixture of VBScript, C#, and Perl to a complex language with a great community.
This book is split into a number of sections. Much of the book is intended to act as a reference. We will cover the following topics in this book:
- Exploring PowerShell fundamentals
- Working with data
- Automating with PowerShell
- Extending PowerShell
In the first section of this book, while exploring the PowerShell fundamentals, we will look at the use of language and cover as many building blocks as possible.
In this chapter, we will briefly look at a number of short, diverse topics:
- What is PowerShell?
- Quick reference
- PowerShell editors
- PowerShell on Linux
PowerShell is a mixture of a command line, a functional programming language, and an object-oriented programming language. PowerShell is based on Microsoft .NET, which gives it a level of open flexibility that was not available in Microsoft's scripting languages (such as VBScript or batch) before this.
PowerShell is an explorer's scripting language. With built-in help, command discovery, and with access to much of the .NET Framework, it is possible to dig down through the layers.
This book is based on PowerShell 5.1; some of the features discussed in the book may not be available in the earlier versions of PowerShell.
There is a wide variety of quick references available for PowerShell. This particular reference is intended to kick-start the book, as a lot of this is either not explicitly explained or used often before in a more detailed explanation.
Refer to the following table:
Line comment |
| # This is a line comment |
Block comment |
| <# This is a block or multi-line comment #> |
Refer to the following table:
Statement separator |
| Get-Command Get-Process; Get-Command Get-Help |
Call operator |
| & ‘Get-Process’ # Invoke the string as a command & { Get-Process –Id $PID } # Invoke the script block |
Dot-source operator |
| . C:\script.ps1 # Execute the script in the current scope (instead of its own scope) |
PowerShell uses a tick as a multipurpose escaped
character.
A tick may be used as a line continuation character. Consider the following example:
'one' -replace 'o', 't' ` -replace 'n', 'w' ` -replace 'e', 'o'
When using a tick to split a long statement across several lines, the tick must be the last character (it cannot be followed by a space or any other character).
A tick is used to construct several characters that can be used in strings:
Description | String | ASCII character code |
Null |
|
|
Bell sound |
|
|
Backspace |
|
|
New page form feed |
|
|
Line feed |
|
|
Carriage return |
|
|
Horizontal tab |
|
|
Vertical tab |
|
|
The tab
character, for example, may be included in a string:
PS> Write-Host "First`tSecond"
First Second
Alternatively, the bell sound may be played in the PowerShell console (but not ISE):
Write-Host "`a"
Refer to the following table:
Equal to |
| 1 –eq 1 # Returns $true 1 –eq 2 # Returns $false |
Not equal to |
| 1 –ne 2 # Returns $true 1 –ne 1 # Returns $false |
And |
| $true –and $true # Returns $true $true –and $false # Returns $false $false –and $false # Returns $false |
Or |
| $true –or $true # Returns $true $true –or $false # Returns $true $false –or $false # Returns $false |
Addition and concatenation |
| 1 + 1 # Equals 2 “one” + “one” # Equals oneone |
Subexpression operator |
| “Culture is $($host.CurrentCulture)” “Culture is $(Get-Culture)” |
Refer to the following table:
Assign to |
| $null = Get-Command |
Cast to |
| [Void](Get-Command) |
Pipe to |
| Get-Command | Out-Null |
Redirect to |
| Get-Command > $null |
Refer to the following table:
Using the array operator |
| $array = @() # Empty array $array = @(1, 2, 3, 4) |
Implicit array |
| $array = 1, 2, 3, 4 $array = “one”, “two”, “three”, “four” |
Using the |
| $hashtable = @{} # Empty hashtable $hashtable = @{Key1 = “Value1”} $hashtable = @{Key1 = “Value1”; Key2 = “Value2”} |
Refer to the following table:
Expanding string |
| “Value” $greeting = “Hello”; “$greeting World” # Expands variable |
Expanding here-string |
| $one = ‘One’ @” Must be opened on its own line. This string will expand variables like $var. Can contain other quotes like “ and ‘. Must be closed on its own line with no preceding white space. “@ |
Non-expanding string |
| ‘Value’ ‘$greeting World’ # Does not expand variable |
Non-expanding here-string |
| @’ Must be opened on its own line. This string will not expand variables like $var. Can contain other quotes like “ and ‘. Must be closed on its own line with no preceding white space. ‘@ |
Quotes in strings |
| “Double-quotes may be escaped with tick like `”.” “Or double-quotes may be escaped with another quote ““.” ‘Single-quotes may be escaped with tick like `’.’ ‘Or single-quotes may be escaped with another quote like ‘‘.’ |
Refer to the following table:
Errors |
| $Error[0] # The last error |
Formats the enumeration limit. Dictates the number of elements displayed for objects with properties based on arrays. The default is |
| $object = [PSCustomObject]@{ Array = @(1, 2, 3, 4, 5) } $object # Shows 1, 2, 3, and 4 $formatenumerationlimit = 1 $object # Shows 1 |
Holds data of the current PowerShell host. |
| $host $host.UI.RawUI.WindowTitle |
The matches found when using the |
| ‘text’ –match ‘.*’ $matches |
The output field separator. The default is a single space. Dictates how arrays are joined when included in an expandable string. |
| $arr = 1, 2, 3, 4 “Joined based on OFS: $arr” $ofs = ‘, ‘ “Joined based on OFS: $arr” |
Current PowerShell process ID. |
| Get-Process –Id $PID |
Holds the path to each of the |
| $profile.AllUsersAllHosts $profile.AllUsersCurrentHost $profile.CurrentUserAllHosts $profile.CurrentUserCurrentHost |
PowerShell version information. |
|
$PSVersionTable.PSVersion |
Present working directory. |
| $PWD.Path |
Refer to the following table:
| Opens PowerShell ISE. Opens a file with ISE if a filename is given. |
| If Visual Studio Code is installed (and in Opens the VS Code. Opens a file or folder with the VS Code. |
| Shows command history for the current session. |
| Autocompletes in context. |
| Autocompletes against history (beginning of the line). Typing |
|
|
|
|
| Runs a process as administrator. |
While it is possible to write for PowerShell using the Notepad application alone, it is rarely desirable. Using an editor designed to work with PowerShell can save a lot of time.
Specialized PowerShell editors, at a minimum, offer automatic completion (IntelliSense) that reduces the amount of cross-referencing required while writing code. Finding a comfortable editor early is a good way to ease into PowerShell: memorizing commands and parameters is not necessary.
Two editors are discussed, as follows:
- PowerShell ISE
- Visual Studio Code
PowerShell IntegratedScriptingEnvironment (ISE) was introduced with PowerShell 2 in October 2009 and has been updated with every subsequent release.
ISE has an immediate advantage over other editors. It is installed along with PowerShell itself and is likely to be available in some form wherever PowerShell is. ISE consists of a text editor pane and a script pane, as shown in the following screenshot:

ISE is a rich editing environment that includes IntelliSense, built-in help, syntax checking, debugging, and so on.
Additional features are available for ISE from the following add-on tools website:
If you are developing code for use on production systems, I strongly recommend adding PS Script Analyzer. PS Script Analyzer will highlight areas of your code that do not conform to its rule set; for example, using an alias instead of a command name would be highlighted.
Community and commercial add-ons can greatly extend the functionality of ISE to simplify day-to-day use.
In PowerShell 5, the distribution model for ISE is in the process of changing. Until version 5, ISE was released as a part of the Windows Management Framework (WMF). New features were introduced with each version of WMF, but the time between the versions was long.
ISE Preview may be installed from the PowerShell gallery using the following command:
Install-Module -Name PowerShellISE-Preview
Once installed, the update-module
command may be used to bring ISE up to par with the published version.
ISE Preview can coexist with the version of ISE installed by the WMF package.
ISE may be started from the start menu; however, running the powershell_ise
command (from the Run
dialog, cmd
, or the search box) is sufficient. In PowerShell, the simpler ise
command is aliased to powershell_ise.exe
.
If the preview version from the PowerShell gallery is being used, the following command will start that version of ISE:
Start-ISEPreview
This first preview version differs a little from the version of ISE shipping with WMF 5. If the distribution model is successful, the PowerShell team hopes to release a new version of ISE every month, with each release fixing bugs and/or adding new features.
Visual Studio Code is a free open source editor published by Microsoft. VS Code may be downloaded from http://code.visualstudio.com.
VS Code is a good choice of editor when working with multiple languages or when specifically looking for an editor that supports Git in a simple manner.
VS Code does not come with the native PowerShell support. It must be added. Once VS Code is installed, open it, and select the EXTENSIONS
button on the left-hand side.
Type PowerShell
in the search dialog box, and install the PowerShell language support:

After installation, the extension provides Syntax highlighting
, testing using PowerShell Script Analyzer
, debugging, and so on.
Unlike ISE, the console (or terminal, as it is named) in VS Code must be configured. By default, the terminal in code uses cmd.exe
.
The following process is used to make the terminal use PowerShell:

- Open
User
Settings
fromFile
and
Preferences
. The same may be achieved by pressing F1 and typinguser settings
followed by return. - This opens two windows: a
Default Settings
file on the left and asettings.json
on the right. The file on the right holds user-specific configuration that overrides or adds to the default. - Expand the
Integrated Terminal
section inDefault Settings
(by clicking on theo9
symbol) to show the default values. - On the right-hand side, enter the following between the curly braces:
"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe"
- Save the changes, then press Ctrl+Shift+' (apostrophe) to open a new PowerShell terminal. Ctrl + ' (apostrophe) toggles the visibility of the terminal window.
Visual Studio Code comes with integrated support for Git version control. Git is a distributed version control system; each developer has a copy of the same repository.
Setting up a repository is simple, as follows:
- Open a folder that contains a project. Then, select the
Git
button (or press Ctrl +Shift +G). - Click on
Initialize git repository
button as shown in the following screenshot:

- Once you have done this, files may be added to version control when committing (applying a change).
Subsequent changes to files may be inspected before committing again:

PowerShell for Linux is, at least at the time of writing, in alpha. The current release is still worth installing even if only to see what having a unified shell may look like.
Note
What about Cygwin?
PowerShell is not the first to give a hint of a single shell across different operating systems. However, until PowerShell matured, it was a serious challenge to manage Windows and Microsoft-based systems from the command line alone.
Some familiarity with Linux is assumed during this process.
This installation is based on PowerShell 6, alpha 12 as the latest at the time of writing. The package can be downloaded from GitHub with yum
, which will also install the dependencies (https://github.com/PowerShell/PowerShell/releases/latest):
- The following command will install PowerShell and any dependencies (
libicu
,libunwind
, anduuid
):
sudo yum install https://github.com/PowerShell/PowerShell/releases/download/v6.0.0-alpha.12/powershell-6.0.0_alpha.12-1.el7.centos.x86_64.rpm
alpha 12 is the latest release but it may not be when you read this.
- PowerShell can be immediately started by running the following command:
powershell
- Create a few files in the
home
directory as a test:
Set-Location ~
1..10 | ForEach-Object { New-Item $_ -ItemType File }
- The previous command creates
10
empty files named1
to10
(with no file extension). Ensure that the new files are now visible usingGet-ChildItem
:
Get-ChildItem
Several of the following used paths are specific to the installed release (in this case, alpha 12).
As with PowerShell on Windows, the PSHOME
variable shows where PowerShell itself has been installed:
PS> $PSHOME
/opt/microsoft/powershell/6.0.0-alpha.12
The paths for module installation may be viewed using the environment variables:
PS> $env:PSMODULEPATH -split ':'
/home/psuser/.local/share/powershell/Modules
/usr/local/share/powershell/Modules
/opt/microsoft/powershell/6.0.0-alpha.12/Modules
Note
Case sensitivity
Linux has a much higher regard for case than Windows. Environment variables, file paths, executables, and so on, are case sensitive. The previously used variable name must be written in uppercase.
Use Get-ChildItem
to list all of the environment variables using the following command:Get-ChildItem env:
Once installed, PowerShell is visible in the list of available shells:
chsh -l
Set PowerShell as the default shell
for the current user:
chsh
New shell [/bin/bash]: /usr/bin/powershell
The current user profile on Linux resides under the home directory:
~/.config/powershell
Two profiles can be created: CurrentUserCurrentHost
(Microsoft.PowerShell_profile.ps1
) and Current User
(profile.ps1
). Inspecting the automatic variable, $PROFILE
shows the first of these:
- The directory will need to be created prior to use; the following command creates it:
New-Item ~/.config/powershell -ItemType Directory
- Create a simple profile file by sending a string to a file:
‘Write-Host “Welcome to PowerShell” -ForegroundColor Green’ | Out-File .config/powershell/profile.ps1
- The
AllUser
profile may be created under PowerShell's installation directory, in this case, alpha 12, as this is the version I have installed:
/opt/microsoft/powershell/6.0.0-alpha.12
- Writing to this area of the filesystem requires the
root
privileges:
sudo vi /opt/microsoft/powershell/6.0.0-alpha.12/profile.ps1
- Inside
vi
, pressi
to enter insert mode and then type the following:
Write-Host 'This is the system profile' -ForegroundColor Yellow
- Once completed, press Esc, then type
:wq
to save and quitvi
. - As with PowerShell on Windows, this will be executed before a user-level
profile
that shows the following in the console when the shell is started:
This is the system profile
Welcome to PowerShell
PowerShell on Linux (and macOS) has a long way to go to reach maturity. Our experience writing for these systems has to make a similar journey.
One of the most important facets is that Linux and macOS run PowerShell Core. It lacks some features we may have become used to when writing for Windows.
Windows editors, including ISE, tend to use a carriage return followed by linefeed (\r\n
or `r`n
) at the end of each line. Linux editors use linefeed only (\n
or `n
).
Line endings are less important if the only thing reading the file is PowerShell (on any platform). However, if a script is set to executable on Linux, a sha-bang must be included and the line-ending character used must be linefeed only.
For example, a created as follows named test.ps1
must use \n
to end lines:
#!/usr/bin/env powershell
Get-Process
The first line is the sha-bang and lets Linux know which parser to use when executing the shell script.
Once created, chmod
may be used to make the script executable outside of PowerShell:
chmod +x test.ps1
After being made executable, the script may be executed from bash
with the full path or a relative path:
./test.ps1
Windows editors, including ISE, tend to save files using what is commonly known as ANSI encoding; this is more correctly known as Windows-1252.
As Windows-1252 is a Microsoft native format, it may be more appropriate to save files in a universally accepted format such as UTF8.
Testing shows that PowerShell on Linux is forgiving about path separators; that is, Microsoft Windows uses the backslash (\
), where Linux uses a forward slash (/
).
If anything outside of PowerShell (including native commands) is to be used, a correct separator should be chosen.
The Join-Path
command will merge path elements using the correct separator for each platform. Manual path construction (based on merging strings) should be avoided.
The following function uses the System.Net.NetworkInformation
namespace to discover IPv4 address information. This allows us to return the same thing whether it is run on Windows or Linux.
If it were Windows only, we might have used WMI or the Get-NetIPConfiguration
command. Creating something to work on both operating systems is more challenging:
function Get-IPConfig { [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ForEach-Object { $ipProperties = $_.GetIPProperties() $addresses = $ipProperties.UnicastAddresses | Where-Object { $_.Address.AddressFamily -eq 'InterNetwork' } | ForEach-Object { "$($_.Address) $($_.IPv4Mask)" } $gateway = $ipProperties.GatewayAddresses.Address | Where-Object { $_.AddressFamily -eq 'InterNetwork' -and $_ -ne '0.0.0.0' } [PSCustomObject]@{ Name = $_.Name Id = $_.Id Addresses = $addresses Gateway = $gateway } } | Where-Object { $_.Addresses } } Get-IPConfig
This chapter featured a brief introduction to PowerShell itself and provided a quick reference for some of the syntax and features.
A reasonable PowerShell editor is a great tool to have for any scripting language. A number of excellent options are available for beginners and veterans alike.
Recently, PowerShell has moved onto GitHub as an open source project. At the same time, versions of PowerShell for Linux and macOS have been developed. Installation of PowerShell on CentOS was briefly demonstrated.
In Chapter 2, Working with PowerShell, we will look at the help system and how to discover commands.