Skip to content
ImagineWorld

Using PowerShell on Linux

node_idnode-book_the-ultimate-linux-shell-scripting-guide_chapter-23-using-powershell-on-linux
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num23
chapter_titleUsing PowerShell on Linux
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

PowerShell started its life as a closed-source, proprietary product that could only be installed on Windows operating systems. Now though, it’s Free Open Source Software, and is freely available for use on Linux-based and macOS-based machines.

I can’t give you a complete course on PowerShell in this chapter, because it’s something that would require an entire book. Instead, I’ll just give you a high-level overview of the PowerShell philosophy, show you how to install it, and provide some useful examples. I’ll also provide some rationale on why you, as a Linux or Mac administrator, might like to learn PowerShell. And of course, you’ll find plenty of PowerShell reference material links both throughout the chapter and in the Further Reading section.

Topics in this chapter include:

  • Installing PowerShell on Linux and macOS
  • Reasons for Linux and Mac Admins to Learn PowerShell
  • Differences Between PowerShell Scripting and Traditional Linux/Unix Scripting
  • Viewing the Available PowerShell Commands
  • Getting Help with PowerShell Commands
  • Real-World Cross-Platform PowerShell Scripts

If you’re ready, let’s get started.

Technical Requirements

You can use a Fedora, Ubuntu, or Debian virtual machine for this. You won’t be using your FreeBSD or OpenIndiana virtual machines, because PowerShell isn’t available for them.

As always, you can grab the scripts by doing:

git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.git

We’ll first look at the methods for installing PowerShell on Linux, and then look at how to install it on macOS.

Installing PowerShell on Linux via a snap Package

Section titled “Installing PowerShell on Linux via a snap Package”

The snapd system is a universal software packaging system that was invented by the developers of Ubuntu. It comes installed by default on Ubuntu operating systems, and can be installed on most other Linux distros.

If you’re setting up a new Ubuntu Server, you can choose to install a selection of snap packages, including PowerShell, from the Ubuntu installer. Here’s what that looks like:

Figure 23.1: Selecting the PowerShell snap package during Ubuntu installation

You can install snapd on non-Ubuntu distros, but the installation instructions vary for different distros. You can find the installation instructions here:

https://snapcraft.io/docs/installing-snapd

Once you’ve installed snapd, you can install PowerShell by doing:

Terminal window
sudo snap install powershell --classic

On a Fedora system, you can use any of several methods for installing PowerShell. For example, you can install it either via a .rpm package, or via a Docker container. You’ll find detailed instructions for each of these methods, along with a few more, here:

https://fedoramagazine.org/install-powershell-on-fedora-linux/

You can install PowerShell on a Mac via the Homebrew system. You’ll find detailed instructions for that here:

https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4

Once PowerShell is installed, invoke it by entering the pwsh command. Your command-prompt will then look something like this:

Terminal window
PS /home/donnie>

Now, before I show you any demos, let’s address the burning question of the day. Why should a Linux or Mac person such as yourself learn a scripting language that was invented at Microsoft?

Reasons for Linux and Mac Admins to Learn PowerShell

Section titled “Reasons for Linux and Mac Admins to Learn PowerShell”

Scripting in PowerShell is a somewhat different experience from scripting in the traditional Linux and Unix shells. But, it’s not hard, and you might even like it once you get used to it. At any rate, there are some valid reasons why a Linux administrator might like to learn PowerShell. Let’s take a look at some of those reasons.

Working with Mixed Operating System Environments

Section titled “Working with Mixed Operating System Environments”

The first reason is simply one of both convenience and flexibility. A lot of enterprises and organizations run a mixed bag of Linux and Windows servers, and usually run Windows on their workstations. It might be helpful if you could run one common scripting language across your Windows and Linux platforms. And, if you’re a Windows administrator who now needs to learn Linux administration, you might find it easier to do it with PowerShell, which you’ll likely already know. In fact, let me tell you a story about my own reason for learning PowerShell.

Throughout the years 2010 and 2011, I worked with a client who had taken on the Nagios company as one of his clients. The Nagios company produces the Nagios network monitoring system, which can monitor pretty much every type of network device. (This includes servers that run either Linux or Windows, as well as various types of networking equipment.) My client’s job was threefold. He was to produce training documentation, conduct Nagios training classes, and fly around the country to set up Nagios monitoring systems for clients of the Nagios company.

Anyway, every time my client needed to do anything with Windows servers, he would turn to me, because I knew Windows Server and he didn’t.

Okay, I’ve been guarding a dark secret, and I hope you won’t think badly of me. It’s just that back in 2006, before I got involved with Linux, I obtained my Microsoft Certified Sys- tems Engineer (MCSE) certification for Windows Server 2003. When I first got into Linux, I thought that I would never use my MSCE training. Boy, was I wrong.

Unfortunately, my MCSE training didn’t include anything about PowerShell, because it hadn’t yet been invented. So, in order to come up with Windows Server monitoring solutions for my client, I had to give myself a crash course on PowerShell scripting.

The bottom line here is that if you’re involved with setting up any kind of network monitoring solution, even if you’re a Linux admin, learning PowerShell could be useful.

The second reason is that in some cases, PowerShell is just easier to deal with. You’ve seen how in the traditional Linux/Unix shell languages, commands to perform a certain task can become quite long and convoluted. For example, let’s say that you want to view all of the system processes that are using 200 Megabytes or more of the machine’s Random Access Memory (RAM), and you want to see only certain fields of the output. The traditional Linux/Unix way of doing this would involve using the ps command with the proper option switches, and then piping the ps output into awk, like this:

Terminal window
donnie@fedora:~$ ps -eO rss | awk -F ' ' '{ if($2 >= (1024*200)) {printf("%s\t%s\t%s\n",$1,$2,$6);}}'
PID RSS COMMAND
3215 338896 /usr/lib64/chromium-browser/chromium-browser
3339 247596 /usr/lib64/chromium-browser/chromium-browser
...
21502 614792 /usr/lib64/firefox/firefox
23451 369392 /usr/lib64/firefox/firefox
donnie@fedora:~$

So, what’s the problem with this? Well first, you need to be familiar with the ps option switches, as well as with the various ps output fields. In this case, the ps -e command shows us something like this:

Terminal window
donnie@fedora:~$ ps -e
PID TTY TIME CMD
1 ? 00:00:04 systemd
2 ? 00:00:00 kthreadd
3 ? 00:00:00 pool_workqueue_release
...

But, that doesn’t show the RSS field, which contains the memory use data that we want to see. So, I’ll add the 0 rss option, so that the final ps command will be ps -eo rss. It should now show something that looks like this:

PID RSS S TTY TIME COMMAND
1 29628 S ? 00:00:04 /usr/lib/systemd/systemd --switched-root
--sys
2 0 S ? 00:00:00 [kthreadd]
3 0 S ? 00:00:00 [pool_workqueue_release]
...
...
27199 0 I ? 00:00:00 [kworker/8:2]
27262 62216 S ? 00:00:00 /usr/lib64/firefox/firefox -contentproc
-child
27300 5060 R pts/1 00:00:00 ps -eo rss
donnie@fedora:~$

The problem now is that that’s more than we want to see. Piping this output into awk will filter out all of the unwanted stuff. But, to use awk, you’ll need to know what’s in every field of the ps output, so that you’ll know what fields to list in the awk command. In this case, we want to see the PID, RSS, and COMMAND fields, which are fields 1, 2, and 6. We want to see all processes for which field 2 has a number that’s greater than 200 Megabytes, which we’re expressing here as (1024*200).

Remember that the true definition of a Megabyte is 1024 Kilobytes. Since awk doesn’t understand measurements in Bytes, Kilobytes, Megabytes, and so forth, you’ll have to express your memory measurements as either a math formula or a normal integer. (The integer product of 1024*200 is 204800.)

Finally, the printf command will print out just the fields that we want to see, with the proper formatting options.

Okay, that’s doable. But, can we simplify that with PowerShell? Let’s see.

Terminal window
PS /home/donnie> Get-Process | Where-Object WorkingSet -ge 200MB
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ------ ------ ------ -- -- ---------------
0 0.00 331.27 40.27 3215 ...10 chromium-browser --enable-n...
0 0.00 227.35 11.00 3674 ...10 chromium-browser --type=ren...
0 0.00 221.48 15.93 3369 ...10 chromium-browser --type=ren...
0 0.00 228.37 19.19 3588 ...10 chromium-browser --type=ren...
...
0 0.00 402.61 271.87 8737 ...10 soffice.bin
0 0.00 971.86 1,004.20 5869 ...12 VirtualBoxVM
PS /home/donnie>

Yeah, I’m thinking that that’s a lot easier. It’s a lot shorter, which will make it less prone to error. The only field name you need to know is the WorkingSet (WS) field, which is equivalent to the RSS field in ps. Also, you see that we can pipe the output of one command (Get-Process) into another command (Where-Object), similarly to how we pipe the output of a Linux/Unix utility into another one. The best part is that this command is so intuitive, that I think you can figure out what it’s doing without me even explaining it.

All right, let’s move on to the next reason for learning PowerShell.

Enhanced Built-in Math Capabilities

If you need to create scripts that are heavy on math, PowerShell might be just what you need. You can do floating point math without loading any external program, and a function library is available for advanced math functions. Let’s look at some examples.

First, let’s do a simple division operation, like so:

Terminal window
PS /home/donnie> 5 / 2
2.5
PS /home/donnie>

As you see, PowerShell does floating point math by default, without having to invoke any special tricks. Now, let’s put some different math problems into the math1.ps1 script, which looks like this:

Terminal window
param([Float]$number1 = "", [Float]$number2 = "")
$sum = $number1 + $number2
Write-Host "The sum of these numbers is: " $sum
Write-Host "************"
$divideresult = $number1 / $number2
Write-Host "Division of these two numbers results in: "$divideresult
Write-Host "************"
$multiplyresult = $number1 * $number2
Write-Host "Multiplying these two numbers results in: " $multiplyresult
Write-Host "************"
$modulo = $number1 % $number2
Write-Host "The remainder from dividing these two numbers is: " $modulo

The first thing to note here is the param line at the top. This is the directive that creates the positional parameters that I’ll use to pass arguments into the script. Instead of using 1and1 and 2 as positional parameters, I’m using param to create the number1andnumber1 and number2 positional parameters. Note how I need to create both positional parameters with just one param directive. If I use two separate param lines, the script will error out, because it won’t recognize the second param line. Also, I’ve specified that the number1 and number2 variables that I’m using for the positional parameters will be of the floating point number type.

The rest of the script is a straightforward demonstration of how to do addition, division, multiplication, and modulo operations. Instead of using echo or printf statements, I’m using PowerShell’s native Write-Host command. Also, note how variable names will always be preceded by a $, whether you’re defining them or calling back their values. Now, let’s run the script with 5 and 2 as our arguments:

Terminal window
PS /home/donnie> . /math1.ps1 5 2
The sum of these numbers is: 7
**********
Division of these two numbers results in: 2.5
**********
Multiplying these two numbers results in: 10
**********
The remainder from dividing these two numbers is: 1
PS /home/donnie>

Easy enough, right? Well, doing more advanced math in PowerShell is just as easy. To demonstrate, let’s create the math2.ps1 script, like so:

Terminal window
param([Float]$number1 = "")
$tangent = [math]::Tan($number1/180*[math]::PI)
Write-Host "The tangent of $number1 degrees is: $tangent."
Write-Host "**********"
$cosine = [math]::Cos($number1/180*[math]::PI)
Write-Host "The cosine of $number1 degrees is: $cosine."
Write-Host "**********"
$squareroot = [math]::Sqrt($number1)
Write-Host "The square root of $number1 is: $squareroot."
Write-Host "**********"
$logarithm = [math]::Log10($number1)
Write-Host "The base 10 logarithm of $number1 is: $logarithm."

Here, you see how I’m using the [math]:: construct to call in the functions that calculate the tangent, cosine, square root, and logarithm of my specified number. The only slight catch is that the tangent and cosine functions work with radians by default. To make it work with degrees, I had to divide the number of degrees that I input by 180, and then multiply that by the value of pi (π).

Terminal window
PS /home/donnie> Get-ChildItem
Directory: /home/donnie
UnixMode User Group LastWriteTime Size Name
---------- ---- ---- ------------ ---- ----
drwx------ donnie donnie 7/4/2024 23:59 4096 demo_files
...
-rw-rw-r-- donnie donnie 9/3/2024 22:26 67 zsh_fruits.txt
-rw-rw-r-- donnie donnie 9/4/2024 18:17 141 zsh_time.sh
PS /home/donnie>

You see that the Get-ChildItem command does pretty much the same job as an ls -l command. On a Windows machine, there will already be a PowerShell alias that allows you to use the ls command to run the Get-ChildItem command. Here’s how that looks on one of my Windows machines:

Figure 23.2: Using the ls PowerShell alias on Windows

So yeah, this looks just like the Get-ChildItem command. But, if you open a PowerShell session on Linux or Mac and run the ls command, you won’t invoke the alias, because no aliases are set up by default. Instead, you’ll invoke the actual ls command from your Linux or Mac operating system. Here’s how that looks:

Terminal window
PS /home/donnie> ls
acl_demo.sh rootlock_1.sh
bashlib-0.4 rootlock_2.sh
date_time.sh rsync_password.sh

You see that this looks nothing like Get-ChildItem. In fact, it’s just the normal output from your normal ls command.

Fortunately though, you can create your own aliases on PowerShell, which can make typing PowerShell commands much easier. You can create aliases with either the Set-Alias or the New-Alias Cmdlets. Let’s first create the alias that will make ls run the Get-ChildItem command, using Set-Alias:

Terminal window
PS /home/donnie> Set-Alias -Name ls -Value Get-ChildItem
PS /home/donnie> ls
Directory: /home/donnie
UnixMode User Group LastWriteTime Size Name
---------- ---- ---- ------------ ---- ----
drwxr-xr-x donnie donnie 6/29/2024 21:10 4096 bashlib-0.4
drwx------ donnie donnie 7/4/2024 23:59 4096 demo_files
. . .
. . .
-rw-rw-r-- donnie donnie 9/3/2024 22:26 67 zsh_fruits.txt
-rwxr-xr-x donnie donnie 9/4/2024 18:17 141 zsh_time.sh
PS /home/donnie>

The other way is to use New-Alias, like so:

Terminal window
PS /home/donnie> New-Alias ls Get-ChildItem
PS /home/donnie>

Either way works equally well, but it’s only a temporary fix. Once you close your PowerShell session, you’ll lose the alias. To make your aliases permanent, you’ll need to edit your PowerShell profile file. You can find where it’s supposed to be by doing:

Terminal window
PS /home/donnie> echo $profile
/home/donnie/.config/powershell/Microsoft.PowerShell_profile.ps1
PS /home/donnie>

The only problem is that the .config/ directory is there, but neither the powershell/ subdirectory nor the Microsoft.PowerShell_profile.ps1 file is. So, you’ll need to create them.

You can just use your normal Linux/Mac command to create the powershell/ subdirectory, like this:

Terminal window
PS /home/donnie> mkdir .config/powershell
PS /home/donnie>

Then, use your favorite text editor to create the Microsoft.PowerShell_profile.ps1 file within that new powershell/ subdirectory. Add this line to create the ls to Get-ChildItem alias:

New-Alias ls Get-ChildItem

You can add as many aliases to this file as you like. Just remember to log out of your PowerShell session, and then log back in to ensure that the new profile takes effect.

Important: If you intend to create PowerShell scripts that will run on multiple machines, be aware that the aliases that you’ve created might not be available on some of them. Your best bet in that case will be to forget about using your own aliases, and just use the native PowerShell commands.

Next, let’s see how to view the available PowerShell Commands.

Viewing the Available PowerShell Commands

To see what commands are available to you, just do:

Terminal window
PS /home/donnie> Get-Command
CommandType Name Version S
----------- ---- ------- -
Alias Get-PSResource 1.0.4.1 M
Function cd..
Function cd\
Function cd~
Function Clear-Host
Function Compress-Archive 1.2.5 M
...
<!-- page: 627 (printed 637) -->
Cmdlet Write-Verbose 7.0.0.0 M
Cmdlet Write-Warning 7.0.0.0 M
PS /home/donnie>

Under CommandType, you see that we have aliases, functions, and Cmdlets. Under the Source column, you see the letter M, which means that these commands are all stored in some PowerShell module.

Of course, there aren’t nearly as many PowerShell commands for Linux as there are for Windows. To see how many there are, just do this:

Terminal window
PS /home/donnie> Get-Command | Measure-Object | Select-Object -Property Count

293

Terminal window
PS /home/donnie>

Here, we begin by piping the output of the Get-Command Cmdlet into the Measure-Object Cmdlet. The official explanation of Measure-Object, according to the help file, is that it calculates the property values of certain types of objects. In this case, we only want to see one of those calculations, which shows us how many commands there are. We’ll do that by piping the Measure-Object output into Select-Object -Property Count, which works the same as the Linux/Unix wc -l command. After all that, we see that there are 293 PowerShell commands available on this Linux machine.

As I’ve mentioned a few pages back in the PowerShell Uses Cmdlets section, all Cmdlets are in the Verb-Noun format. You can use Get-Command with either the -Verb or -Noun options to see all of the commands for a particular verb or noun. For example, let’s see all of the available commands for the Date noun:

Terminal window
PS /home/donnie> Get-Command -Noun 'Date'

CommandType Name Version Source


Cmdlet Get-Date 7.0.0.0 M Cmdlet Set-Date 7.0.0.0 M

Terminal window
PS /home/donnie>

We see that there are only two Cmdlets for Date. Let’s see how many there are for the Set verb:

Terminal window
PS /home/donnie> Get-Command -Verb 'Set'
CommandType Name Version Source
----------- ---- ------- ------
Function Set-HostnameMapping 1.0.1 H
Function Set-PSRepository 2.2.5 P
Cmdlet Set-Alias 7.0.0.0 M
Cmdlet Set-Clipboard 7.0.0.0 M
...
Cmdlet Set-StrictMode 7.4.5.500 M
Cmdlet Set-TraceSource 7.0.0.0 M
Cmdlet Set-Variable 7.0.0.0 M
PS /home/donnie>

If you’re wondering how to find out what all of these PowerShell commands do. Well, let’s look at that next.

This one is easy. Just use the Get-Help Cmdlet, followed by the name of the command for which you need information. For example, you can see information about the Get-Module Cmdlet like this:

Terminal window
PS /home/donnie> Get-Help Get-Module

What you’ll see will resemble a normal Linux/Unix man page.

At the bottom of every Get-Help screen, you’ll see commands that will show you how to see even more information. For example, if you need to see examples of how to use the Get-Module Cmdlet, do this:

Terminal window
PS /home/donnie> Get-Help Get-Module -Examples

Sometimes, the help page for the command that you need to learn about isn’t available. In those cases, either run the Update-Help Cmdlet, or append the -Online option to the end of your Get-Help command.

Another great resource is the PowerShell Commands page, which you can find here: https://ss64.com/ps/ (Of course, a lot of the listed commands are Windows-specific, but you’ll also find quite a few that are cross-platform.)

Okay, I think that this does it for the PowerShell theory. Let’s look at a couple of real-world examples of PowerShell scripts.

Real-World Cross-Platform PowerShell Scripts

Section titled “Real-World Cross-Platform PowerShell Scripts”

To come up with some real-world examples of cross-platform PowerShell scripts, I did a DuckDuckGo search for the PowerShell script examples Linux text string. The coolest thing I found is the Mega Collection of PowerShell Scripts on Github. You can use git to download it by doing:

Terminal window
git clone https://github.com/fleschutz/PowerShell.git

Once it’s downloaded, cd into the PowerShell/scripts/ directory, and take a look at what’s there. For our first example, let’s look at something simple that will run on all platforms.

The write-marquee.ps1 script is truly cross-platform, because it doesn’t use any commands that are specific to any particular operating system. All it does is create a marquee message that flows across on your screen. I can’t show the entire script here, but you can look at your own local copy. So, let’s just look at the individual parts of it to see how it’s set up.

At the top, you see the comment section, which is surrounded by <# and #>. Actually, these are more than just comments. If you do Get-Help ./write-marquee.ps1, you’ll see that everything that’s within the <# and the #> will come up as a help screen, like this:

Terminal window
PS /home/donnie/PowerShell/scripts> Get-Help ./write-marquee.ps1
NAME
/home/donnie/PowerShell/scripts/write-marquee.ps1
SYNOPSIS
Writes text as marquee
· · ·
· · ·
REMARKS
To see the examples, type: "Get-Help /home/donnie/PowerShell/scripts/write-
marquee.ps1 -Examples"
<!-- page: 630 (printed 640) -->
For more information, type: "Get-Help /home/donnie/PowerShell/scripts/
write-marquee.ps1 -Detailed"
For technical information, type: "Get-Help /home/donnie/PowerShell/scripts/
write-marquee.ps1 -Full"
For online help, type: "Get-Help /home/donnie/PowerShell/scripts/write-marquee.ps1 -Online"
PS /home/donnie/PowerShell/scripts>

Next, the param([string]$Text line creates the string-type variable that contains the marquee message. It looks like this:

Terminal window
param([string]$Text = "PowerShell is powerful - fully control your computer!
PowerShell is cross-platform - available for Linux, Mac OS and Windows!
PowerShell is open-source and free - see the GitHub repository at github.com/PowerShell/PowerShell! PowerShell is easy to learn - see the tutorial
for beginners at guru99.com/powershell-tutorial.html! Powershell is fully
documented - see the official PowerShell documentation at docs.microsoft.com/
en-us/powershell", [int]$Speed = 60) # 60 ms pause

The [int]$Speed = 60) # 60 ms pause part at the end of the variable definition determines the speed at which the marquee message will flow across the screen.

Next up is the StartMarquee function, which looks like this:

Terminal window
function StartMarquee { param([string]$Line)
$LinePos = $HOST.UI.RawUI.CursorPosition
$LinePos.X = 2
$LinePos.Y -= 2
foreach($Pos in 1 .. $($Line.Length - 80)) {
$HOST.UI.RawUI.CursorPosition = $LinePos
Write-Host -noNewLine "$($Line.Substring($Pos,80))"
Start-Sleep -milliseconds $Speed
}
}

Figure 23.3: The StartMarquee function

After drawing the marquee box and using $LinePos lines to ensure that everything gets properly positioned, you see the foreach loop that prints the message out to the screen, one letter at a time.

Finally, after the function definition, you see the function call:

Terminal window
StartMarquee "
+++ $Text +++ $Text +++ $Text +++ $Text +++ $Text +++ $Text +++ $Text
+++ $Text +++ $Text +++ $Text +++ $Text +++ $Text +++ $Text +++ $Text
<!-- page: 631 (printed 641) -->
"
exit 0 # success

The function call passes the Textvariable,whichcontainsthemarqueemessage,intotheStartMarqueefunction.InbetweeneachiterationoftheText variable, which contains the marquee message, into the StartMarquee function. In between each iteration of the Text message, there will be three plus signs (+++). The script will keep running until it’s gone through all iterations of the $Text message. Anyway, here’s how it looks when I run it on my Ubuntu Server virtual machine:

Terminal window
PS /home/donnie/PowerShell/scripts> .\write-marquee.ps1
our computer! PowerShell is cross-platform - available for Linux, Mac OS and Win

Figure 23.4: Running the write-marquee.ps1 script

Pretty cool, eh? Now, let’s look at something that’s even more cool.

The check-cpu.ps1 Script

The check-cpu.ps1 script attempts to retrieve the model number and name of your machine’s CPU, along with the CPU temperature.

If you want to see the CPU temperature, you’ll need to run this directly on a host Linux machine, instead of in a virtual machine. Running this in a virtual machine won’t allow the script to access the host machine’s temperature sensors.

I say attempt, because when I run this script on my Fedora workstation, I get this:

Terminal window
PS /home/donnie/PowerShell/scripts> .\check-cpu.ps1
✓ 64-bit CPU (16 cores, ) - 48°C OK
PS /home/donnie/PowerShell/scripts>

So, all it shows me is that I’m running some sort of 64-bit CPU with 16 cores. The actual truth is that this machine is running an Intel(R) Xeon(R) CPU E5-2670, with eight cores and hyperthreading enabled. But, if I run this same script on a Windows 10 machine, I’ll get this:

Terminal window
PS C:\Users\donni\Documents\PowerShell\scripts> .\check-cpu.ps1
Intel(R) Core(TM)2 Quad CPU Q9550 @ 2.83GHz (AMD64, 4 cores, CPU0, 2833MHz, CPU socket) - no temp
PS C:\Users\donni\Documents\PowerShell\scripts>

Figure 23.5: The check-cpu.ps1 script on a Windows machine

On this ancient (circa 2008) Dell that’s running Windows 10 Pro, the script properly reports that the CPU is an old-school Core 2 Quad, model number Q9550. On the other hand, the script properly reported the CPU temperature on the Linux machine, but not on the Windows machine. That part is easy to explain. It’s just that some computer motherboards, especially older ones, have temperature sensors that aren’t compatible with modern operating systems.

As far as getting the CPU model right, it seems that the PowerShell command for Linux can’t do that, but the command for Windows can. Let’s take a look at the script to see what’s going on with that.

Toward the top of the check-cpu.ps1 script, you see the GetCPUArchitecture function, which looks like this:

Terminal window
function GetCPUArchitecture {
if ("$env:PROCESSOR_ARCHITECTURE" -ne "") { return "$env:PROCESSOR_ARCHITECTURE" }
if ($IsLinux) {
$Name = $PSVersionTable.OS
if ($Name -like "*-generic *") {
if ([System.Environment]::Is64BitOperatingSystem) {
return "x64" } else { return "x86" }
} elseif ($Name -like "*-raspi *") {
if ([System.Environment]::Is64BitOperatingSystem) {
return "ARM64" } else { return "ARM32" }
} elseif ([System.Environment]::Is64BitOperatingSystem) {
return "64-bit" } else { return "32-bit" }
}
}
}

As you see, there’s a bit of difference in the syntax from what you’re used to in normal Linux/Unix scripting. One difference is that instead of surrounding a test condition with square brackets, PowerShell uses parentheses. Like this, for example:

Terminal window
if ("$env:PROCESSOR_ARCHITECTURE" -ne "") { return "$env:PROCESSOR_ARCHITECTURE" }

All this line does is to return the value of the PROCESSOR_ARCHITECTURE environmental variable, if one exists. The rest of this function is specifically for Linux, as evidenced by the if (IsLinux) stanza. You see here that it detects whether the CPU is x86, x86_64, or ARM. For ARM, it detects whether it’s a 32-bit or 64-bit version.

The only part of this function that Windows uses is the first line, which is the if (“env:PROCESSOR_ARCHITECTURE" -ne "") { return "env:PROCESSOR_ARCHITECTURE” } line. And, the only thing that this does on my Windows 10 machine is to insert the “AMD64” string into the information that you see in the above graphic. On Windows, all other CPU information is obtained from the Windows Management Instrumentation (WMI) interface. The code for that is in the else clause of the try stanza, which begins on line 44. (The else clause begins on line 54.) Here’s how it looks:

Terminal window
try {
Write-Progress "Querying CPU status..."
$status = "✓"
$arch = GetCPUArchitecture
}
if ($IsLinux) {
$cpuName = "$arch CPU"
$arch = ""
$deviceID = ""
$speed = ""
$socket = ""
}
else {
$details = Get-WmiObject -Class Win32_Processor
$cpuName = $details.Name.trim()
$arch = "$arch, "
$deviceID = "($($details.DeviceID), "
$speed = "($($details.MaxClockSpeed)MHz, "
$socket = "($($details.SocketDesignation) socket"
}

You see in the if..else construct that if the machine is running Linux, it will call the GetCPUArchitecture function, and retrieve the CPU information from it. In the else section, you see the code for Windows. Although the script does obtain one piece of information for Windows from the PROCESSOR_ARCHITECTURE environmental variable, it obtains most of the CPU information from the Windows Management Instrumentation (WMI) subsystem. As it happens, the PROCESSOR_ARCHITECTURE variable doesn’t contain any information for this particular Fedora workstation. So, all I get on this machine is just the generic message about whether I’m running a 32-bit or 64-bit machine, and whether it’s an x86 or an ARM machine. That’s okay though, because I can modify the script to fix that.

Open the check-cpu.ps1 script in your editor, and scroll down until you see this line in the try stanza, which should be line 47:

Terminal window
$arch = GetCPUArchitecture

We’re going to leave that line alone, because Windows also uses the GetCPUArchitecture function. Instead, we’re going to add the following line after the if ($IsLinux) { line, which is line 48:

Terminal window
$arch = Get-Content /proc/cpuinfo | Select-String "model name" | Select-Object -Unique

Instead of obtaining its value from the GetCPUArchitecture function, the arch variable now gets its value from a command substitution construct.

We see here a couple of other ways in which PowerShell scripting is different.

First, anytime you work with a PowerShell variable, you need to precede the variable name with a .Thismeansthatwhetheryou′redefiningavariableorcallingbackitsvalue,youneedthat. This means that whether you're defining a variable or calling back its value, you need that . Secondly, you see that in PowerShell, you don’t surround the command substitution construct with $(). Instead, just write the command as you normally would.