Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Powershell Core 6.2 Cookbook
Powershell Core 6.2 Cookbook

Powershell Core 6.2 Cookbook: Leverage command-line shell scripting to effectively manage your enterprise environment

Arrow left icon
Profile Icon Jan-Hendrik Peters
Arrow right icon
€8.99 €26.99
eBook Apr 2019 372 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Jan-Hendrik Peters
Arrow right icon
€8.99 €26.99
eBook Apr 2019 372 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Powershell Core 6.2 Cookbook

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/installation for 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 Linuxthere 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-Help cmdlet 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 FilePath parameter 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 CurrentUser command 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 PSModulePath environmental variable in order to find all modules that have the HelpInfoUri property 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-Help cmdlet 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-Help cmdlet 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-Help cmdlet 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.

See also

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 DoesNotExist cmdlet 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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • A recipe-based guide to help you build effective administrative solutions
  • Gain hands-on experience with the newly added features of PowerShell Core
  • Manage critical business environments with professional scripting practices

Description

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.

Who is this book for?

This book will be for windows administrators who want to enhance their PowerShell scripting skills to the next level. System administrators wanting to automate common to complex tasks with PowerShell scripts would benefit from this book. Prior understanding on PowerShell would be necessary.

What you will learn

  • Leverage cross-platform interaction with systems
  • Make use of the PowerShell recipes for frequent tasks
  • Get a better understanding of the inner workings of PowerShell
  • Understand the compatibility of built-in Windows modules with PowerShell Core
  • Learn best practices associated with PowerShell scripting
  • Avoid common pitfalls and mistakes

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 19, 2019
Length: 372 pages
Edition : 1st
Language : English
ISBN-13 : 9781789809435
Vendor :
Microsoft
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 19, 2019
Length: 372 pages
Edition : 1st
Language : English
ISBN-13 : 9781789809435
Vendor :
Microsoft
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 124.97
Powershell Core 6.2 Cookbook
€32.99
Mastering Windows PowerShell Scripting
€41.99
Windows Server 2019 Automation with PowerShell Cookbook
€49.99
Total 124.97 Stars icon
Banner background image

Table of Contents

13 Chapters
Introduction to PowerShell Core Chevron down icon Chevron up icon
Reading and Writing Output Chevron down icon Chevron up icon
Working with Objects Chevron down icon Chevron up icon
Mastering the Pipeline Chevron down icon Chevron up icon
Importing, Using, and Exporting Data Chevron down icon Chevron up icon
Windows and Linux Administration Chevron down icon Chevron up icon
Windows Server Administration Chevron down icon Chevron up icon
Remoting and Just Enough Administration Chevron down icon Chevron up icon
Using PowerShell for Hyper-V and Azure Stack Management Chevron down icon Chevron up icon
Using PowerShell with Azure and Google Cloud Chevron down icon Chevron up icon
Accessing Web Services Chevron down icon Chevron up icon
High-Performance Scripting Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.