Powershell Core 6.2 Cookbook

4.6 (5 reviews total)
By Jan-Hendrik Peters
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to PowerShell Core

About this book

This book will follow a recipe-based approach and start off with an introduction to the fundamentals of PowerShell, and explaining how to install and run it through simple examples. Next, you will learn how to use PowerShell to access and manipulate data and how to work with different streams as well. You will also explore the object model which will help with regard to PowerShell function deployment. Going forward, you will get familiar with the pipeline in its different use cases. The next set of chapters will deal with the different ways of accessing data in PowerShell. You will also learn to automate various tasks in Windows and Linux using PowerShell Core, as well as explore Windows Server. Later, you will be introduced to Remoting in PowerShell Core and Just Enough Administration concept. The last set of chapters will help you understand the management of a private and public cloud with PowerShell Core. You will also learn how to access web services and explore the high-performance scripting methods.

By the end of this book, you will gain the skills to manage complex tasks effectively along with increasing the performance of your environment.

Publication date:
April 2019
Publisher
Packt
Pages
372
ISBN
9781789803303

 

Chapter 1. Introduction to PowerShell Core

PowerShell Core, as the open source alternative to Windows PowerShell from which it evolved, is quickly becoming the automation engine of choice for many administrators and developers alike. As a true cross-platform shell, PowerShell Core is perfectly suited for many different operating system types and workloads.

While the next iteration of PowerShell Core at the time of writing was slated for May 2019 and will drop the Core this book and its recipes will remain accurate and useful. The release of PowerShell is merely a rebranding to unify PowerShell development. In the future we will continue to see rapid new iterations of PowerShell.

While installing PowerShell Core is a breeze, the first steps for people new to PowerShell can be quite challenging. In this chapter, I aim to bridge those little knowledge gaps and show you the ropes.

You'll learn all there is to know about installing and operating PowerShell Core and learn about the cmdlets necessary to find your way on any system running PowerShell Core. In addition to that, you'll discover how to get help without using the internet and do everything from within PowerShell.

This chapter is intended for beginners who are fairly new to PowerShell Core and will help you understand the very basics of PowerShell while the next chapters assume solid scripting knowledge.

In this chapter, we will cover the following recipes:

  • Installing PowerShell Core on Windows
  • Installing PowerShell Core on Linux
  • Running PowerShell Core
  • Getting help
  • Getting around
  • How do cmdlets work?
  • Performing read-only operations
  • Introducing change to systems
  • Discovering the environment
 

Technical requirements


In order to follow the recipes in this chapter, you need a machine capable of running PowerShell Core that is connected to the internet.

 

Installing PowerShell Core on Windows


In this recipe, you'll learn how to provision PowerShell Core on a Windows system starting with Windows 6.1 (Server 2008 R2/Windows 7).

Getting ready

To follow this recipe, you'll need a Windows machine with at least Windows Server 2008 R2 or Windows 7. If this machine isn't connected to the internet, you'll need a way of transferring the installer to the machine.

How to do it...

Please perform the following steps:

  1. In order to get the most recent release of PowerShell Core for Windows, browse to https://github.com/powershell/powershell:
  1. Download the release for your platform. I recommend using the stable 64 bit (x64) edition if possible.

 

  1. Open the installer file, for example, PowerShell-6.2.0-win-x64.msi.
  2. Follow the instructions on screen to install PowerShell Core
  3. On the final page, you can directly enable PowerShell remoting if you want. Leave the option disabled for now; you'll configure it properly later on:
  1. Start PowerShell Core by typing pwsh into the search bar!

How it works...

Using the standard MSI installer methods, PowerShell Core will be installed for your system in the 64 bit Program Files directory by default. It won't replace Windows PowerShell but will simply coexist peacefully and include the most recent updates to PowerShell.

If left on the default settings, an event manifest will be registered on the system, enabling an event log for PowerShell Core. The log file will be placed at %SystemRoot%\System32\Winevt\Logs\PowerShellCore%4Operational.evtx and can be found in the Applications and Services Logs.

By default, no remoting configuration will be made. We'll talk about remoting in Chapter 8, Running Remote Commands and Understanding Just Enough Administration, where you'll enable PowerShell remoting for a system.

 

There's more...

Besides the installer that you can download and install manually or through any software deployment solution, you can also use Chocolatey. Chocolatey is a NuGet package source for binary packages and can be used to bootstrap software on a system.

The following steps will install Chocolatey and PowerShell Core on a Windows system. These steps require using Windows PowerShell for the initial process:

  1. Run the following command in Windows PowerShell (see https://chocolatey.org/docs/installationfor details): 
Set-ExecutionPolicy Bypass -Scope Process -Force
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
  1. After the installation of Chocolatey, simply execute choco install powershell /y.
  2. Start PowerShell Core by searching for pwsh in the search bar!

If you're so inclined, compiling the code from scratch is of course also an option. Simply follow the guidelines laid out in the GitHub repository to do so:

# Clone the repository
git clone https://github.com/powershell/powershell

Set-Location -Path .\powershell
Import-Module ./build.psm1

# Ensure you have the latest version of .NET Core and other necessary components
Start-PSBootStrap

# Start the build process
Start-PSBuild

# Either run PowerShell directly...
& $(Get-PSOutput)

# ...or copy it to your favorite location (here: Program Files on Windows, necessary access rights required)
$source = Split-Path -Path $(Get-PSOutput) -Parent
$target = "$env:ProgramFiles\PowerShell\$(Get-PSVersion)"
Copy-Item -Path $source -Recurse -Destination $target

 

 

 

 

 

 

 

 

 

 

See also

 

Installing PowerShell Core on Linux


Since the arrival of PowerShell Core, its key feature has been the ability to run cross-platform and provide the exact same experience on any operating system. Installing PowerShell on Linux is nearly as easy as it is in Windows. If your distribution is among the list of supported distributions such as CentOS, openSUSE, or Ubuntu, the process is pretty straightforward.

Getting ready

In order to follow the recipe, you'll need any Linux distribution (even the Windows Subsystem for Linux) that's preferably connected to the internet and can download packages. In the recipe, I'm using CentOS and Ubuntu to show some very different approaches.

At the time of writing, the recipe was correct. However, check whether it still applies on the official installation page for your operating system, for example, https://docs.microsoft.com/en-us/powershell/scripting/setup/installing-powershell-core-on-linux.

How to do it...

On CentOS 7.x, perform the following steps:

  1. Register the Microsoft RPM repository: 
curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo.
  1. Install the package: sudo yum install -y powershell.
  2. Run PowerShell by executing pwsh, which is now installed.

On Ubuntu 18.10, perform the following steps:

  1. Open the Ubuntu Software store.
  2. Search for powershell:
  1. Install and run PowerShell Core:

The steps to install PowerShell on other distributions are fairly similar as long as you can use your distribution's package management system, such as rpm or dpkg.

How it works...

Usually, the installation instructions for Linux require the registration of a package repository that's maintained by Microsoft and used to publish PowerShell Core. The repository settings include the URL, a reference to the GPG public key, and the status of the repository.

On Linux, binary packages are usually compiled using a makefile on the running OS and then, for example, linked or copied to one of the binary paths. The best example for this is probably Gentoo, where compiling your kernel and all components, libraries, and software is actually required. With RPM and DEB packages, developers can better resolve dependencies and include all necessary instructions to install a binary package or compile a source package.

With binary packages, the component is compiled for a specific architecture with general compilation flags set. While this won't allow the user to fine-tune every part of the installation, it'll provide the benefit of an easier deployment.

PowerShell comes pre-built in, for example, an RPM package for different OS architectures. By using the package management provider of the distribution, you ensure that all necessary dependencies are installed alongside the package itself.

With Ubuntu 18.10, PowerShell is available as a Snap package in the Ubuntu Software store. This allows a more user-friendly installation of PowerShell that doesn't require the command line at all—apart from using PowerShell, of course.

There's more...

There're many different flavors of Linux—there is macOS, Windows, and probably other platforms to come. Stay up-to-date by having a look at the official installation instructions at https://github.com/powershell/powershell.

In addition to traditional installation methods, you can also build your entire PowerShell from scratch.

See also

 

Running PowerShell Core


Using PowerShell Core is very simple. This recipe will show you the very first steps and help you to run PowerShell Core after the installation.

Getting ready

In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system.

How to do it...

Let's perform the following steps:

  1. On Windows, run pwsh.exe. On Linux or macOS, run pwsh.
  2. Type your first cmdlet, Get-Process, to retrieve a list of running processes on the system and hit Enter to confirm.
  3. Compare the output of the cmdlet with the output of tasklist (in Windows) and ps (in Linux):
  1. Type Get-Date and hit Enter to confirm.
  1. Compare the output of this cmdlet with the output of date /t (in Windows) and date (in Linux):
  1. Execute the line: Get-Process | Where-Object -Property WorkingSet -gt 100MB.
  2. Compare the output again with the output of tasklist /FI "MEMUSAGE gt 102400" (in Windows) and ps -aux | awk -F" " '$5 > 102400' (in Linux):
  1. Lastly, execute this cmdlet: Stop-Computer -WhatIf. This time, there's no comparable command on either Windows or Linux.

How it works...

PowerShell works with commands like any other shell environment. Native PowerShell commands are called cmdlets. Unlike commands from other shells, PowerShell cmdlets should only serve one purpose and fulfill this purpose only. As always, there're exceptions to the rule. In some cases, command-line switches, called switch parameters, can be used to toggle additional functionality.

The first example, Get-Process, returns (Get) a list of running processes (Process). While the formatted output appears similar to that of the Windows command tasklist, PowerShell doesn't merely return text, but .NET objects.

Our second example, Get-Date, returns the current date and time as a .NET object again. In .NET, time is calculated with ticks, which are 100 nanosecond-intervals starting at 0001-01-01 00:00:00. The output is formatted depending on your operating system's culture and can be changed on demand.

The third example has you filter the output with PowerShell, which is extremely easy compared to Windows and Linux alike. Especially the endless possibilities of working with text in Linux make this a striking example. The ps command doesn't allow much filtering, so you need to rely on tools such as awk to process the text that is returned. This simple task without PowerShell requires knowledge of text processing and filtering with different tools.

The last cmdlet, Stop-Computer, demonstrates a very common parameter with many cmdlets called WhatIf. This parameter allows you to simply try a cmdlet before actually doing anything. This is an excellent way to test changes for general correctness, for example, before modifying your 10.000 Active Directory user accounts:

There's more...

There's plenty more to do and see in PowerShell—part of which will be covered in this book. Try to follow the upcoming recipes as well to find out about cmdlet discovery, the flow between cmdlets in the pipeline, and much more.

See also

 

Getting help


Help is never far away in PowerShell Core and, in this section, you'll learn how to utilize the help to your benefit.

Getting ready

In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system.

How to do it...

Please perform the following steps:

  1. Open PowerShell Core.
  2. Type the Get-Helpcmdlet and hit Enter. The cmdlet displays help about the help system.
  1. Use the -?parameter with any cmdlet, for example, Start-Process -?. Notice the output after this cmdlet. You can see the syntax of the cmdlet, as well as some additional remarks:
  1. Type the Get-Help Start-Process -Parameter FilePath command. Note the output at that point. Only help for the FilePathparameter is returned. From the output, you can see that the parameter is mandatory, has two aliases, and doesn't like pipeline input:
  1. Type the Get-Help Start-Process -Full command. You can notice in the output that indeed no help files have been downloaded yet.
  1. Type the Update-Help -Scope CurrentUsercommand to download all current help content.
  2. Examine the folder contents of $home\Documents\PowerShell\Help in Windows and  ~/.local/share/powershell in Linux.
  3. Type the Update-Help -Module CimCmdlets -UICulture ja-jp,sv-se command. Notice that not all modules provide localized help content—the content in en-us should be available for most modules, however.
  4. Now that the help content has downloaded, try Get-Help Start-Process -Full again.
  5. Notice that now the full content is available, allowing you to get additional information about a cmdlet.

How it works...

The help system of PowerShell Core can be used to update help files from the internet or from a CIFS share. Without updated help content, the help system always displays the name and syntax of a cmdlet as well as detailed parameter help for all parameters of a cmdlet.

In order to update help for modules on the local system, Update-Help will examine all modules in the PSModulePathenvironmental variable in order to find all modules that have the HelpInfoUriproperty set. It'll try to resolve the URI, which should point to a browsable website where it will then look for an XML file called <ModuleName>_<ModuleGuid>_HelpInfo.xml. Inside this XML file, the location of a cabinet file (*.cab) is stored, which will then be used to download the actual content.

With the new Scope parameter introduced in PowerShell Core, all help content will be placed in the personal user folder, for example, C:\Users\<UserName>\Documents\PowerShell, instead of a system-wide folder that would require administrative privileges, for example, C:\Program Files\PowerShell.

The Update-Helpcmdlet will only download new content once per day if the cmdlet is called. In order to download the content more frequently, you can use the Force parameter.

There's more...

Help content can also be hosted on-premises by using the Save-Helpcmdlet and distributing the content. On Windows systems, a group policy setting can be found that can control the default path for Update-Help as well. This setting is in Administrative Templates | Windows Components | System | Windows PowerShell. This setting is only valid for Windows PowerShell. Regardless of the edition, the Update-Helpcmdlet supports the SourcePath parameter to specify from where the help content will be downloaded.

In order to provide your own help content properly, have a look at the PowerShell module, PlatyPS. This module makes it very easy to generate help content for your own modules, package it to the correct format, and much more.

PlatyPS supports markdown help, enabling you to write help content in a very easy way that feels more natural than creating large and complex MAML files.

 

Getting around


In this section, you'll learn how to get around on any system running PowerShell Core through cmdlet discovery.

Getting ready

In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system.

How to do it...

Please perform the following steps:

  1. Open PowerShell Core.
  2. Type Get-Command. Notice that all available cmdlets on the system will be displayed. Depending on the modules installed on your system, this will be a lot.
  3. Type Get-Command New-Item -Syntax. Notice that, this time, it's not the cmdlet that's returned, but the syntax that's displayed:
  1. Type Get-Command -Verb Get -Module Microsoft.PowerShell.Utility. Notice here that all read-only cmdlets of a specific module are returned, thereby greatly narrowing down the results:
  1. Type Get-Command -CommandType Application. This time, all external applications (in other words, binaries) are returned. Try to favor native PowerShell cmdlets over external applications where possible:
  1. Type Get-Command -ParameterName ComputerName,CimSession,PSSession. This is one of my favorites; with this parameter, only cmdlets that have certain parameters are returned. In this instance, all remote-capable cmdlets will be returned. This parameter, however, only searches through all cmdlets available in the current session:
  1. Type Get-Command *Process,*Item. Notice that, this time, a wildcard search is performed on all cmdlets that exist on the system.
  2. Type New-Alias -Name Start-Process -Value hostname and then type Get-Command Start-Process. Only the alias will be returned now, effectively hiding the cmdlet, Start-Process.
  3. Type Get-Command Start-Process -All. This time, the alias as well as the original cmdlet are returned.

How it works...

PowerShell and its incredibly flexible system are easily discovered with the help of Get-Command. Even for a seasoned PowerShell expert, Get-Command is invaluable as it works on any system, doesn't need additional content, and will save you precious time. Additionally, nobody is able to just know all existing cmdlets—sometimes, you just need to have a short look at the syntax.

Aliases are a part of PowerShell as well as cmdlets. Sometimes, an alias is introduced when the name of a cmdlet changes in order maintain backward compatibility to some degree. Other aliases are simply created to make working interactively faster or to ease the migration from another scripting language such as the aliases, dir and ls.

By inspecting module manifests and module definitions, Get-Command is able to discover the exported cmdlets of a module that make up the available cmdlets on a system. Additionally, the PATH environmental variable is used to discover external applications such as executables, libraries, and text files.

The output of Get-Command can simply be filtered with wildcards in order to discover cmdlets that have a certain purpose, for example, *Process will list all cmdlets that have something to do with processes.

One parameter that you should always use is the Syntax parameter. Reading the cmdlet syntax is one of the easiest ways to determine how the cmdlet can be used, what its mandatory parameters are, and what its parameter values should look like.

There's more...

Even if you're an advanced PowerShell user, Get-Command can help you. Just have a look at the amount of data you can access for each command by using Format-List. We'll later learn about Get-Member as well:

# Discover more about a cmdlet with Format-List
Get-Command New-Item | Format-List -Property *

# Examine additional properties that might be helpful
$cmd = Get-Command New-Item

# Where does the cmdlet's help content come from?
$cmd.HelpUri

# Quickly jump to the location of a cmdlet's module
Set-Location -Path $cmd.Module.ModuleBase

# How many parameters does a cmdlet have including the common parameters?
$cmd.Parameters.Count

# Discovering the data of a parameter, in this case realizing that
# New-Item allows empty strings or $null to be passed to the Name parameter
$cmd.Parameters.Name

Look at the following screenshot of how the output looks:

See also

 

How do cmdlets work?


In contrast to native OS commands such as ps on Linux or tasklist on Windows, PowerShell uses cmdlets. These cmdlets always follow the same, simple syntax. Moreover, specifying parameters and their values always works the same with every cmdlet as well.

This section will help you to understand how cmdlets work before diving into them in later chapters.

Getting ready

In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system.

How to do it...

Please perform the following steps:

  1. Start PowerShell Core.
  2. Type New-Item -Path variable: -Name myVariable -Value "Isn't it great?.
  3. Type $myVariable. $myVariable is a variable—a temporary storage space for your data. Just executing the variable will place it on the output.
  4. Type Get-ChildItem $home *.*. This cmdlet uses no parameter names, and only parameter values. $home is a built-in variable and *.* filters for all files with a dot in the name.
  5. Type Get-ChildItem *.txt $home. Observe the error this time. You can't mix positional parameters.
  6. Type Get-ChildItem -Filter *.txt -Path $home. By using the parameter names, the cmdlet works again.
  7. Type $processName  = 'powershell'. Assigning anything to a variable like this will store the result in the variable.
  8. Type Get-Process $processName.
  9. Type Get-Process $pid. As opposed to the process name, using an ID will fail the cmdlet.
  10. Type Get-Process -Id $pid. By using the correct parameter, the cmdlet works again.
  11. Type Get-Command -Syntax -Name Get-Process. Observe the syntax of the cmdlet; there's more than one way to execute a cmdlet. These are called parameter sets.

How it works...

Native PowerShell cmdlets should all follow the exact same syntax: verb-noun. The verb indicates the action and the noun indicates the recipient of that action. Whether it is a cmdlet such as New-Item or Get-Process, the syntax always follows the same principle.

With all of its different parameters used, a full cmdlet call might look like the following example:

Get-ChildItem $home -Filter *.txt -File

Get-ChildItem is the name of the cmdlet. $home is the value of a so-called positional parameter, Path. -Filter uses the parameter name, and *.txt is the value provided for that parameter. -File is something called a switch parameter, which resembles a command-line switch.

 

Performing read-only operations


Very often, PowerShell is used to gather data for reporting purposes, exporting and viewing configurations, and more. This is generally accomplished using the various Get cmdlets. In Chapter 2, Reading and Writing Output, we'll then see how to further process the gathered data.

Since the Get cmdlets won't change anything on your system, this is a great way to discover what PowerShell has to offer.

Getting ready

In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system. Some cmdlets are Windows-specific and require a Windows operating system.

How to do it...

Please perform the following steps:

  1. On a Windows system, you can use many built-in cmdlets with PowerShell Core. Try Import-Module Storage -SkipEditionCheck.
  2. On a Windows system, type Get-Disk to list all disks. The result should look similar to the following:
  1. On a Windows system, use Get-Disk -Number 0 | Get-Partition to retrieve the partitions on the first disk:
  1. On any system, try the Get-Uptime cmdlet to calculate the system uptime.
  2. Use Get-Culture and Get-UICulture to view the current language settings.
  3. Review the result of Get-PackageProvider. On a Windows system, additional providers are visible.

How it works...

PowerShell provides access to several different data sources by means of the Get cmdlets. After retrieving the data, PowerShell wraps it into an object model to allow you to store, display, filter, and process the data.

The data sources can be anything from services, event logs, and files to functions and variables. Every item that's retrieved is called an object and will have different properties and methods, which we will see later on.

There's more...

Just explore Get-Command -Verb Get to find all read-only cmdlets and simply have a look at what the return values are. There's no harm in trying!

On your way to building a perpetuum mobile? Make PowerShell execute all Get cmdlets for some fun:

$ErrorActionPreference = 'SilentlyContinue'
Get-Command -Verb Get | ForEach-Object { & $_ }

The ampersand operator will invoke an expression. By iterating over each Get cmdlet that is returned by Get-Command, we try to read everything we can get our hands on. Please be aware that this will take some time.

 

Introducing change to systems


While reading data is usually fine, PowerShell is also a great automation engine that's able to change a system configuration. We'll explore a couple of cmdlets that will, in some form, change your system configuration.

Getting ready

In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system. You should prepare a virtual machine for testing purposes since the cmdlets used in this recipe will inadvertently change your system configuration. 

How to do it...

Please perform the following steps:

  1. Review the output of Get-Command -Verb New,Set,Remove,Register,Unregister,Start,Stop to review some of the more frequently used cmdlets.
  2. Execute $file = New-TemporaryFile to create a temporary file.
  3. Use 'SomeContent' | Set-Content -Path $file to change the file contents.
  4. Use 'More content!' | Add-Content -Path $file to append data to the file.
  5. Review the contents with $file | Get-Item | Get-Content -Path.
  6. Lastly use $file | Remove-Item -Verbose to get rid of the file again.
  7. Use $ping = Start-Process -FilePath ping -ArgumentList 'packtpub.com' -PassThru.
  8. Use $ping | Stop-Process -PassThru to stop the background process.
  1. Use Start-Job -Name Sleepy { Start-Sleep -Seconds 100; Get-Date}.
  2. Have a look at the job with Get-Job -Name Sleepy—is it ready to deliver the data?
  3. Use Get-Job -Name Sleepy | Wait-Job to wait for the results.
  4. Lastly, use Get-Job -Name Sleepy | Receive-Job -Keep to gather the results.
  5. As an alternative, try $job = Get-ChildItem -Recurse -Force -Path $home & and $job | Wait-Job | Receive-Job.
  6. Clean up any remaining jobs by closing PowerShell or executing $job | Remove-Job; Get-Job -Name Sleepy | Remove-Job.

How it works...

There're many verbs in PowerShell that indicate changes such as New, Set, and Remove. Many of those cmdlets also return objects for the data that's altered or created. If one of those parameters doesn't provide output such as Stop-Process, you can try using the PassThru parameter if it is available. It usually means that objects will be returned.

In the recipe, you can see the usual flow between different cmdlets. The file can be created, modified, and removed using the pipeline and cmdlets related to each other. In Chapter 2, Reading and Writing Output, we'll see how pipeline input is usually processed.

With the new parameter, &, you can start a background job, much like the forking parameter on Linux. The job results can be collected later as well.

There's more...

There're countless cmdlets that change a running system, some of which we will see in this book. Be sure to have a look at the PowerShell repository on GitHub and the documentation on https://docs.microsoft.com/en-us/ to get all available information before ruining your weekend or your colleague's on-call shift.

See also

 

Discovering the environment


PowerShell Core has plenty of built-in variables that give you immediate information about the environment you are working with. The following recipe will show you the most important ones.

Getting ready

In order to follow this recipe, you should have completed the installation of PowerShell Core for your operating system.

How to do it...

Please perform the following steps:

  1. Review the output of $PSVersionTable. With this variable, you'll always know which version and edition you are running.
  2. Try to execute Set-Location $PSHome; Get-ChildItem. This folder contains all PowerShell binaries necessary to run the shell.
  3. Have a look at the value of $pid. This variable always points to your own PowerShell process.
  4. Try running the Get-Item DoesNotExistcmdlet and afterward, view the contents of $Error. This variable collects errors that happen in your session. Not all errors collected here have been visible on the CLI.
  5. Try the following: $true = $false. You'll be pleasantly surprised that these variables are so-called constants and can't be changed.
  6. Have a look at the output of Get-Process | Format-Table Name,Threads. You'll notice that the threads always seem to stop at four elements.
  7. Display the contents of the variable, $FormatEnumerationLimit. The value of four isn't a coincidence. This variable governs how list output is formatted.
  8. Have a look at $PSScriptRoot. For some reason, this variable is empty. The reason is that this variable is only set when a script is executed. It then will point to the directory containing the script. $PSCommandPath will contain the entire script path.
  1. Run the following command: Set-Content -Path ~/test.ps1 -Value '$PSScriptRoot;$PSCommandPath'; ~/test.ps1. Examine the output; the first line contains the script directory, whereas the second line will show the full script path you executed.
  2. Lastly, try Get-Variable *Preference. These variables control the behavior of PowerShell regarding errors, warnings and more. In Chapter 2, Reading and Writing Output, we'll have a close look at those.

How it works...

Each time a new PowerShell session is started, a bunch of variables is registered and filled. You can always rely on those variables to exist and be present in your scripts. Many of those variables contain preferences for cmdlets, formatting, and output.

There's more...

In the following chapters, there'll be more. We'll continue using the built-in variables for different purposes.

About the Author

  • Jan-Hendrik Peters

    Jan-Hendrik Peters is an automation and DevOps professional by day, and a developer for the AutomatedLab framework by night. After working at an international retailer automating distributed POS support systems, he started working as a premier field engineer for Microsoft Germany, where he helps customers automate their infrastructure on-premises and in the cloud.

    When he is not working, he likes to spend his time brewing his own beer, curing his own bacon, and generally doing manual labor.

    Browse publications by this author

Latest Reviews

(5 reviews total)
I expected a book about Microsoft Powershell but I learned new things anyway.
A good quick start on a new release of PS.
Everything worked! And the course - although not yet finished - was of course good.

Recommended For You

Windows Server 2019 Automation with PowerShell Cookbook - Third Edition

Automate Windows server tasks with the powerful features of the PowerShell Language

By Thomas Lee
Mastering Windows Server 2019 - Second Edition

Enhance and secure your datacenter with the newest Microsoft server platform

By Jordan Krause
Active Directory Administration Cookbook

Learn the intricacies of managing Azure AD, Azure AD Connect as well as Active Directory for administration on cloud and Windows Server 2019

By Sander Berkouwer
Networking Fundamentals

Become well-versed with basic networking concepts such as routing, switching, and subnetting, and prepare for the Microsoft 98-366 exam

By Gordon Davies