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
€36.99
Paperback Nov 2018 566 pages 1st Edition
eBook
€20.98 €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
€36.99
Paperback Nov 2018 566 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 : 9781789137231
Vendor :
Microsoft
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Nov 30, 2018
Length: 566 pages
Edition : 1st
Language : English
ISBN-13 : 9781789137231
Vendor :
Microsoft
Languages :
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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela