Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
PowerShell Core for Linux Administrators Cookbook
PowerShell Core for Linux Administrators Cookbook

PowerShell Core for Linux Administrators Cookbook: Use PowerShell Core 6.x on Linux to automate complex, repetitive, and time-consuming tasks

Arrow left icon
Profile Icon Prashanth Jayaram Profile Icon Ram Iyer
Arrow right icon
€29.99
eBook Nov 2018 566 pages 1st Edition
eBook
€29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Prashanth Jayaram Profile Icon Ram Iyer
Arrow right icon
€29.99
eBook Nov 2018 566 pages 1st Edition
eBook
€29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€29.99
Paperback
€36.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
Table of content icon View table of contents Preview book icon Preview Book

PowerShell Core for Linux Administrators Cookbook

Preparing for Administration Using PowerShell

In this chapter, we will cover the following topics:

  • Installing Visual Studio Code
  • Configuring automatic variables
  • Changing the shell behavior using variables
  • Enabling automated execution of commands for each load
  • Customizing the Terminal prompt
  • Understanding standard redirection in PowerShell
  • Calling native Linux commands from PowerShell
  • Understanding cmdlets and parameters
  • Running cmdlets with minimal keystrokes
  • Finding parameter aliases
  • Calling a PowerShell script
  • Dot-sourcing a PowerShell script
  • Calling a PowerShell cmdlet from outside of PowerShell
  • Recording the cmdlets run on the PowerShell console

Introduction

It is a common notion that the more you use the Terminal (as opposed to the GUI), the more efficient you are. Typing out commands is much easier and faster than clicking around the screen. However, to someone who has just begun using the Terminal, it may not be so. Over time, as administrators grow more and more comfortable with the Terminal, they learn to configure it for speed and efficiency, much like training a horse. Further, most efficient administrators like automating several parts of their workflow—customizing .bashrc and Vim scripts are examples of this. In this chapter, we will familiarize ourselves with the different consoles and tools that work with PowerShell, and will also look at a few simple recipes that would help customize our workspace, so that we can be more efficient.

Installing Visual Studio Code

Scripting can happen on the console itself, with Vim. It is also possible to use other editors, such as Gedit or even Atom, to write PowerShell scripts. It is, however, recommended to use Microsoft's open source code editor, called Visual Studio Code (or vscode). In this recipe, we will look at installing Visual Studio Code and configuring it to work with PowerShell.

Getting ready

We will look at the steps to install vscode on Ubuntu. Today, most repositories contain Visual Studio Code. You can check in the software store of your distribution to install vscode. If not, the easiest way to install vscode is to download the .deb (or the .rpm package if you are on CentOS) and run it to install...

Configuring automatic variables

Perhaps nothing contributes to efficiency like configurability. Configuring a system is a way of tuning it to your taste. You are the only one who knows what works best for you. Therefore, the more configurable a system is, the better it can be tweaked to your preference. Automatic variables in PowerShell are one of the first steps to customization in PowerShell (profiles are the other; we shall look into them shortly). In this recipe, we will list out all of the automatic variables and configure some of them to our requirements.

Getting ready

Read the Listing the various providers in PowerShell recipe of Chapter 1, Introducing PowerShell Core, to learn how to use the various providers in PowerShell...

Changing shell behavior using variables

In the previous recipe, we took a look at the existing variables. In this recipe, we will change the value of one of the variables to control the behavior of PowerShell. Again, remember that the change in the value is ephemeral; the values would be reset once the PowerShell process is restarted.

Getting ready

Read the previous recipe to understand the automatic variables that come predefined. Also, start Visual Studio Code. Perform the following steps to start Visual Studio Code:

  1. Open applications (I use the GNOME desktop environment, which shows all applications with Super + A).
  2. Type in code.
  3. Press Ctrl + ` to launch the Terminal.
  4. Click on New File on the welcome screen (or press Ctrl...

Enabling automated execution of commands for each load

As we saw in the previous recipes, these changes are ephemeral; they remain as long as the session is active. There might be situations where administrators might require running a few commands or loading modules to enable them to work faster. For instance, I tend to load a series of modules that help me manage Microsoft Exchange, Active Directory, VMware vSphere infrastructure, Citrix XenApp, Microsoft System Center, and other environments using PowerShell.

All of these products require different ways of loading the modules, snap-ins, and scripts, and many of them require a certain configuration every time you load the modules (such as connecting to VM servers with administrator credentials). These can be done using the PowerShell profile.

...

Customizing the Terminal prompt

In the previous recipe, we customized the error action preference using the profile. We used an already-demonstrated command to show that commands that can be run on the PowerShell console can be added to the profile as well, and this was a way to automate running a certain set of commands which could be used to increase productivity.

Now, we will take the next step and customize our console prompt. The options are theoretically endless; this recipe is just another demonstration of how flexible PowerShell is.

Getting ready

You need Visual Studio Code for this recipe. If you did not follow along with the last recipe, follow the steps in the Getting ready section of the last recipe to create...

Understanding standard redirection in PowerShell

During the process of learning to use Bash or sh, we learn to use the redirection operators, such as <, >, and >>. PowerShell works on redirection as well. However, the implementation of redirection is different in PowerShell.

Redirection in PowerShell mainly relies on streams, which are covered in a different chapter. For this recipe, we stick with the default stream, which is Success. This recipe covers different, simple redirections to help with basic administration.

Before we begin, let us understand that PowerShell is very different from Bash in terms of redirection, although it packs some minor similarities; similarities enough to make you not go away, but rather appreciate the flexibility of the object model and the uniformity of use.

...

Calling native Linux commands from PowerShell

In Chapter 1, Introducing PowerShell Core, we saw how native Linux commands were not convenience aliases in PowerShell on Linux, but the commands themselves. In this recipe, we will demonstrate using Linux commands at the PowerShell prompt. Remember, we used a Bash Terminal to run the ls -l and awk commands to list the contents of a directory and separate the columns in the output in the recipe, Comparing the outputs of Bash and PowerShell in Chapter 1, Introducing PowerShell Core. We will perform the same operation on the home directory, from within PowerShell, without using any of the PowerShell cmdlets.

Getting started

It is recommended that you have a Windows PC with PowerShell...

Understanding cmdlets and parameters

Most of our scripting and administration is going to revolve around running cmdlets and chaining them. In some situations, we run a cmdlet expecting it to work a certain way, only to find out that the cmdlet threw an error, or worse, did something undesirable.

The key to getting cmdlets to do what we want them to do is to eliminate ambiguity. In this recipe, we will learn to construct commands contextually and effectively.

Getting ready

Read the Help section of Chapter 1, Introducing PowerShell Core. Let us understand the notifications used in the help information that Get-Help shows.

While this may not be an exhaustive guide to using the help information, it should cover most of your daily...

Running cmdlets with minimal keystrokes

Commands have been made to be short, historically. However, the situation turned into a dilemma over time, since shorter commands meant that they had to be remembered and longer commands meant more keystrokes.

PowerShell has long commands; however, it deals with them in two ways:

  • Aliases, which tend to be shorter
  • Tab completion, which require more keystrokes than aliases, but doesn't require remembering much

The first way necessitates using our memory to recall command names as required. The second, on the other hand, solves the keystroke issue efficiently.

Bash users are used to getting a list of matches laid out in a nice tabular format when the Tab key matches more than one string in the context. On the other hand, the matches cycle at the cursor in Windows (which most Bash users find weird).

Be that as it may, tab completion is...

Finding parameter aliases

We worked with aliases for cmdlets, we saw how to uniquely identify parameter names without having to type the entire parameter name, and we looked at leveraging the power of tab completion.

To complete the cycle, let's also look at parameter aliases.

As you may have guessed, parameter aliases work very similar to cmdlet aliases. The primary goal of these aliases is to reduce keystrokes.

Parameter aliases are not documented in a friendly way, but they can be easily found thanks to the object-oriented model of PowerShell. In this recipe, we will look at how to fetch parameter aliases.

Getting ready

Find all of the commands that take in ComputerName as a parameter, with minimal keystrokes...

Calling a PowerShell script

PowerShell scripts are nothing but a series of PowerShell cmdlets, each in a line of a ps1 file. These instructions are executed one after the other, similar to the good old shell script. Using Visual Studio Code makes running PowerShell scripts simpler, in that you simply have to run the script to make the script work its magic.

However, running PowerShell scripts on Visual Studio Code is not the usual way of automation for obvious reasons. Also, there are many ways to run a PowerShell script. We shall look at a very simple way of running the script in this recipe; as we progress in this book, we will also add more features to our scripts and, further, will package them into modules for future use.

Getting ready

...

Dot-sourcing a PowerShell script

In the previous recipe, we saw how to call PowerShell scripts from outside of the IDE. We gave PowerShell the path and explicitly mentioned that we would like it to run the script, by using a call operator.

This way is ideal if you would just like the script to perform its task and not leave anything behind, such as variable values. However, there are situations where we would like to run a script and, say, retain values of the variables we declared and assigned in them or use the functions we declared in them.

In such situations where we would like the functions, variables, and even aliases retained in the current session, we use dot-sourcing.

How to do it...

If you deleted the file after...

Calling a PowerShell cmdlet from outside of PowerShell

So far we have learned how to call cmdlets from the console, run scripts at the IDE, and call scripts in two modes. In this very short recipe, we shall learn how to call a PowerShell cmdlet from outside of PowerShell.

How to do it...

  1. Open a Terminal window.
  2. At the prompt, type the following:
$ pwsh -h
  1. Read the syntax for the command.
  1. At the prompt, type the following:
$ pwsh -c Get-ChildItem
  1. Let us now run the hello-world.ps1 script:
$ pwsh -f ./Documents/code/github/powershell/chapter-3/hello-world.ps1

How it works...

...

Recording the cmdlets run on the PowerShell console

Often, there are situations in which you perform a series of tasks on your PowerShell console and, after quite some trial and error, come across a solution. And then you wish you had recorded everything you did on the console. You could still copy content from the console, so you try to scroll up. But you can only go so far. Your command history (a little like Bash history) can help you, but sometimes, that feels limited as well.

A few months ago, we were troubleshooting a sync issue between two of their software update distribution systems, which were supposed to work in sync. After some of us were done beating around the GUI, we decided to pick PowerShell to fix the issue. We ran a series of commands and, after a few hours of fighting with the systems, they yielded and we were back up and running.

Our managers asked for all...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Work effectively on Windows, Linux, and macOS with PowerShell’s object-oriented approach and capabilities
  • Handle structured data seamlessly without the need for manual parsing
  • Enhance your native Linux capabilities with PowerShell Core 6.1

Description

PowerShell Core, the open source, cross-platform that is based on the open source, cross-platform .NET Core, is not a shell that came out by accident; it was intentionally created to be versatile and easy to learn at the same time. PowerShell Core enables automation on systems ranging from the Raspberry Pi to the cloud. PowerShell Core for Linux Administrators Cookbook uses simple, real-world examples that teach you how to use PowerShell to effectively administer your environment. As you make your way through the book, you will cover interesting recipes on how PowerShell Core can be used to quickly automate complex, repetitive, and time-consuming tasks. In the concluding chapters, you will learn how to develop scripts to automate tasks that involve systems and enterprise management. By the end of this book, you will have learned about the automation capabilities of PowerShell Core, including remote management using OpenSSH, cross-platform enterprise management, working with Docker containers, and managing SQL databases.

Who is this book for?

PowerShell Core for Linux Administrators Cookbook is for you if you are a system administrator who wants to learn to control and automate a Linux environment with PowerShell Core 6.1. Basic knowledge of PowerShell scripting is necessary. It is assumed that you already understand how an operating system is structured and how to use the command-line interface to work with the operating system.

What you will learn

  • Leverage the object model of the shell, which is based on .NET Core
  • Administer computers locally as well as remotely using PowerShell over OpenSSH
  • Get to grips with advanced concepts of PowerShell functions
  • Use PowerShell for administration on the cloud
  • Know the best practices pertaining to PowerShell scripts and functions
  • Exploit the cross-platform capabilities of PowerShell to manage scheduled jobs, Docker containers and SQL Databases

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2018
Length: 566 pages
Edition : 1st
Language : English
ISBN-13 : 9781789138870
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 Details

Publication date : Nov 30, 2018
Length: 566 pages
Edition : 1st
Language : English
ISBN-13 : 9781789138870
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 110.97
Linux Administration Cookbook
€36.99
PowerShell Core for Linux Administrators Cookbook
€36.99
Learn PowerShell Core 6.0
€36.99
Total 110.97 Stars icon

Table of Contents

18 Chapters
Introducing PowerShell Core Chevron down icon Chevron up icon
Preparing for Administration Using PowerShell Chevron down icon Chevron up icon
First Steps in Administration Using PowerShell Chevron down icon Chevron up icon
Passing Data through the Pipeline Chevron down icon Chevron up icon
Using Variables and Objects Chevron down icon Chevron up icon
Working with Strings Chevron down icon Chevron up icon
Flow Control Using Branches and Loops Chevron down icon Chevron up icon
Performing Calculations Chevron down icon Chevron up icon
Using Arrays and Hashtables Chevron down icon Chevron up icon
Handling Files and Directories Chevron down icon Chevron up icon
Building Scripts and Functions Chevron down icon Chevron up icon
Advanced Concepts of Functions Chevron down icon Chevron up icon
Debugging and Error Handling Chevron down icon Chevron up icon
Enterprise Administration Using PowerShell Chevron down icon Chevron up icon
PowerShell and Cloud Operations Chevron down icon Chevron up icon
Using PowerShell for SQL Database Management Chevron down icon Chevron up icon
Using PowerShell with Docker 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.