Book Image

PowerShell Core for Linux Administrators Cookbook

By : Prashanth Jayaram, Ram Iyer
Book Image

PowerShell Core for Linux Administrators Cookbook

By: Prashanth Jayaram, Ram Iyer

Overview of this book

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.
Table of Contents (19 chapters)

Parsing input from text to object

Moving to the object model from text could seem a little daunting at first. However, with PowerShell, it is not very hard to switch to the new model, especially given that PowerShell can convert text into objects given the right tools. In this recipe, we will look at two of the ways that PowerShell converts textual data into objects.

Getting ready

Before we dive into the recipe, let's give ourselves a little introduction to how text-to-object parsing is handled. One way is to use .NET's built-in functionality, and the second way involves using a cmdlet to perform the conversion based on a delimiter.

The basic requirement for this recipe is simple: you simply need PowerShell installed on your computer. We will edit the file within PowerShell. If you would be more comfortable using a text editor instead, that works as well. Most Linux distributions pack a text editor. If not, use your package manager to install Vim, Nano, Gedit, Visual Studio Code, Atom, or any other text/code editor.

How to do it...

First, we will look at converting text into an object from a plain text input at the Terminal. This involves using what is known as a PowerShell Type Accelerator. A PowerShell Type Accelerator is an alias for .NET classes. Using these, we can call .NET classes and use many of their functionalities within PowerShell:

  1. Let's take plain text as input and convert the text into a date object. To check what sort of object your input is, use the Get-Member cmdlet:
PS> '21 June 2018' | Get-Member
Enclosing any text within single quotes defines the text as a non-expanding literal string. No explicit definition is required in this case.
  1. The TypeName says System.String. This confirms that what we entered was plain text. Now, let's use a Type Accelerator (or, more specifically, a cast operator) and convert this text into a DateTime object. The accelerator for this purpose is [DateTime]; place this accelerator before the literal string:
PS> [DateTime]'21 June 2018'

Thursday, 21 June 2018 00:00:00
  1. Next, find the TypeName of the object that was returned:
PS> [DateTime]'21 June 2018' | Get-Member

TypeName: System.DateTime

Voila, the string has been successfully parsed into date and time!

  1. It is also possible to achieve the same result with the Get-Date cmdlet when it is called with the text argument:
PS> Get-Date '21 June 2018'

Thursday, 21 June 2018 00:00:00
  1. Similarly, the TypeName would be as follows:
PS> Get-Date '21 June 2018' | Get-Member

TypeName: System.DateTime

  1. Just like we did in the previous recipe, we can now manipulate the object to show information in a more meaningful way. For instance, if you care only about the year, you would write the following:
PS> (Get-Date '21 June 2018').Year
2018

The other way of converting text into an object is to use cmdlets that perform such tasks. PowerShell packs a few converter cmdlets, one of which is Import-Csv. You may have noticed that PowerShell usually generates output in a tabular format. This is a simple representation of objects. The Import-Csv cmdlet converts data in a delimited row-and-column structure into objects, where each row is an instance of the object itself, and each column is a property of the object:

  1. To demonstrate this, let's create a CSV file with the following content in it. At the PowerShell prompt, type/paste in the following:
PS> @'
WS,CPU,Id,SI,ProcessName
161226752,23.42,1914,1566,io.elementary.a
199598080,77.84,1050,1040,gnome-shell
216113152,0.67,19250,1566,atom
474685440,619.05,1568,1566,Xorg
1387864064,1890.29,15720,1566,firefox
'@ | Out-File sample.csv
You could perform the same operation using the touch command and the text editor of your choice. The goal is to get the content into the sample file.
  1. Next, read the contents of the file using PowerShell:
PS> Get-Content ./sample.csv
  1. That looks like simple text. Let's look at the type name of the object to confirm that this is indeed plain text. Type in the following:
PS> Get-Content ./sample.csv | Get-Member

TypeName: System.String
  1. That is a plain and simple string. Now, let's convert the content into a simple object. This is done using Import-Csv:
PS> Import-Csv ./sample.csv

That should give you a list-like output, like so:

  1. To confirm that the output is objects, list out its members:

In general, the content is a custom object, which is denoted by PSCustomObject. The columns we had in the CSV are of type NoteProperty, as shown by MemberType.

A NoteProperty is a generic property whose characteristics are similar to those of a string. While most properties are inherited from .NET, NoteProperty is custom-created within PowerShell as a name-value pair.

  1. If you would rather look at the content as a table, format the content as a table. You can do this by using the following command:
PS> Import-Csv ./sample.csv | Format-Table

We have successfully converted text into an object. However, note that this is just a simple conversion, and that the output of Import-Csv is still string-like. Although all of the content is now string-based objects, these are easier to handle in PowerShell.

Also note that Format-Table and other Format-* cmdlets output strings. These are among the handful of PowerShell cmdlets that do not generate a .NET object. Therefore, do not use any of these format cmdlets if you would like to process an object further. The format cmdlets should only be used at the end of the pipeline.

How it works...

Type accelerators are another form of encapsulation of .NET code in PowerShell. Recall the first recipe in this chapter, wherein we created a .NET object within PowerShell. We used the PowerShell command New-Object -TypeName System.IO.DirectoryInfo -ArgumentList '/home/ram' to get information on a home directory: we created a new instance of System.IO.DirectoryInfo and passed an argument to it. That was a lot of code to write. To accelerate this process, we could use [IO.DirectoryInfo]'/home/ram' (System is the default namespace; PowerShell will understand it without us explicitly mentioning it when calling accelerators), which outputs the same object as the former command.

With Import-Csv, on the other hand, the process is a simple conversion of data from text into name-value pairs. This is similar to using ConvertFrom-Text with a Delimiter parameter. This way, we instruct PowerShell to convert each row of text into instances of the object: the first row in the row-column structure is taken as the property name, and the rest of the rows are data. The cells are separated using a delimiter, which was a comma in the case of the CSV file.

There's more...

Look for more conversion cmdlets that are built into PowerShell. This can be done using the Get-Command -Verb ConvertFrom command.

See also