Install PowerShell on Fedora Linux

Photos by NOAA and Cedric Fox on Unsplash

PowerShell (also written pwsh) is a powerful open source command-line and object-oriented shell developed and maintained by Microsoft. It is syntactically verbose and intuitive for the user. This article is a guide on how to install PowerShell on the host and inside a Podman or Toolbox container.

Table of contents

Why use PowerShell

PowerShell, as the name suggests, is powerful. The syntax is verbose and semantically clear to the end user. For those that don’t want to write long commands all the time, most commands are aliased. The aliases can be viewed with Get-Alias or here.

The most important difference between PowerShell and traditional shells, however, is its output pipeline. While normal shells output strings or character streams, PowerShell outputs objects. This has far reaching implications for how command pipelines work and comes with quite a few advantages.

Demonstration

The following examples illustrate the verbosity and simplicity. Lines that start with the pound symbol (#) are comments. Lines that start with PS > are commands, PS > being the prompt:

# Return all files greater than 50MB in the current directory.
## Longest form
PS > Get-Childitem | Where-Object Length -gt 50MB
## Shortest form (with use of aliases)
PS > gci | ? Length -gt 40MB
## Output looks like this
    Directory: /home/Ozymandias42/Downloads 
Mode                 LastWriteTime         Length Name 
----                 -------------         ------ ---- 
-----          20/08/2020    13:55     2000683008 40MB-file.img


# In order: get VMs, get snapshots, only select the last 3 and remove selected list:
PS > Get-VM VM-1 | Get-Snapshot | Select-Object -Last 3 | Remove-Snapshot

What this shows quite well is that input-output reformatting with tools like cut, sed, awk or similar, which Bash scripts often need, is usually not necessary in PowerShell. The reason for this is that PowerShell works fundamentally different than traditional POSIX shells such as Bash, Zsh, or other shells like Fish. The commands of traditional shells are output as strings whereas in PowerShell they are output as objects.

Comparison between Bash and PowerShell

The following example illustrates the advantages of the object-output in PowerShell in contrast to the traditional string-output in Bash. Suppose you want a script that outputs all processes that occupy 200MB or more in RAM. With Bash, this might look something like this:

$ ps -eO rss | awk -F' ' \ 
    '{ if($2 >= (1024*200)) { \
        printf("%s\t%s\t%s\n",$1,$2,$6);} \
     }'

PID    RSS     COMMAND
A      B       C
[...]

The first obvious difference is readability or more specifically, semantic clarity. Neither ps nor awk are self-descriptive. ps shows the process status and awk is a text processing tool and language whose letters are the initials of its developers’ last names, Aho, Weinberger, Kernighan (see Wikipedia). Before contrasting it with PowerShell however, examine the script:

  • ps -e outputs all running processes;
  • -O rss outputs the default output of ps plus the amount of kilobytes each process uses, the rss field; this output looks like this:
    PID  RSS   S TTY TIME     COMMAND  1    13776 S ?   00:00:01 /usr/lib/systemd/systemd
  • | pipe operator uses the output of the command on the left side as input for the command on the right side.
  • awk -F’ ‘ declares “space” as the input field separator. So going with the above example, PID is the first, RSS the second and so on.
  • ‘{ if($2 >= (1024*200) is the beginning of the actual AWK-script. It checks whether field 2 (RSS) contains a number larger than or equal to 1024*200KB (204800KB, or 200MB);
  • { printf(“%s\t%s\t%s\n”,$1,$2,$6);} }’ continues the script. If the previous part evaluates to true, this outputs the first, second and sixth field (PID, RSS and COMMAND fields respectively).

With this in mind, step back and look at what was required for this script to be written and for it to work:

  • The input command ps had to have the field we wanted to filter against in its output. This was not the case by default and required us to use the -O flag with the rss field as argument.
  • We had to treat the output of ps as a list of input fields, requiring us to know their order and structure. Or in other words, we had to at least know that RSS would be the second field. Meaning we had to know how the output of ps would look beforehand.
  • We then had to know what unit the data we were filtering against was in as well as what unit the processing tool would work in. Meaning we had to know that the RSS field uses kilobytes and that awk does too. Otherwise we would not have been able to write the expression ($2 <= 1024*200)

Now, contrast the above with the PowerShell equivalent:

# Longest form
PS > Get-Process | Where-Object WorkingSet -ge 200MB
# Shortest form (with use of aliases)
PS > gps | ? ws -ge 200MB

NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
------    -----      -----     ------      --  -- -----------
     A        B          C          D       E   F           G
[...]

This first thing to notice is that we have perfect semantic clarity. The commands are perfectly self-descriptive in what they do.

Furthermore there is no requirement for input-output reformatting, nor is there concern about the unit used by the input command. The reason for this is that PowerShell does not output strings, but objects.

To understand this think about the following. In Bash the output of a command is equal to that what it prints out in the terminal. In PowerShell what is printed on the terminal is not equal to the information, that is actually available. This is, because the output-printing system in PowerShell also works with objects. So every command in PowerShell marks some of the properties of its output objects as printable and others not. However, it always includes all properties, whereas Bash only includes what it actually prints. One can think of it like JSON objects. Where output in Bash would be separated into “fields” by a delimiter such as a space or tab, it becomes an easily addressable object property in PowerShell, with the only requirement being, that one has to know its name. Like WorkingSet in the above example.

To see all available properties of a command’s output objects and their types, one can simply do something like:

PS > Get-Process | Get-Member

Install PowerShell

PowerShell is available in several package formats, including RPM used by Fedora Linux. This article shows how to install PowerShell on Fedora Linux using various methods.

I recommend installing it natively. But I will also show how to do it in a container. I will show using both the official Microsoft PowerShell container and a Fedora Linux 30 toolbox container. The advantage of the container-method is that it’s guaranteed to work, since all dependencies are bundled in it, and isolation from the host. Regardless, I recommend doing it natively, despite the official docs only explicitly stating Fedora Linux releases 28 to 30 as being supported.

Note: Supported means guaranteed to work. It does not necessarily mean incompatible with other releases. This means, that while not guaranteed, releases higher than 30 should still work. They did in fact work in our tests.

It is more difficult to set up PowerShell and run it in a container than to run it directly on a host. It takes more time to install and you will not be able to run host commands directly.

Install PowerShell on a host using the package manager

Method 1: Microsoft repositories

Installation is as straight-forward as can be and the procedure doesn’t differ from any other software installed through third party repositories.

It can be split into four general steps:

  1. Adding the new repository’s GPG key
  2. Adding repository to DNF repository list
  3. Refreshing DNF cache to include available packages from the new repository
  4. Installing new packages

Powershell is then launched with the command pwsh.

$ sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc
$ curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo
$ sudo dnf makecache
$ sudo dnf install powershell
$ pwsh

To remove the repository and packages, run the following.

$ sudo rm /etc/yum.repos.d/microsoft.repo
$ sudo dnf remove powershell

Method 2: RPM file

This method is not meaningfully different from the first method. In fact it adds the GPG key and the repository implicitly when installing the RPM file. This is because the RPM file contains the link to both in it’s metadata.

First, get the .rpm file for the version you want from the PowerShell Core GitHub repository. See the readme.md
“Get Powershell” table for links.

Second, enter the following:

$ sudo dnf install powershell-<version>.rhel.7.<architecture>.rpm

Substitute <version> and <architecture> with the version and architecture you want to use respectively, for example powershell-7.1.3-1.rhel.7.x86_64.rpm.

Alternatively you could even run it with the link instead, skipping the need to download it first.

$ sudo dnf install https://github.com/PowerShell/PowerShell/releases/download/v<version>/powershell-<version>.rhel.7.<architecture>.rpm

To remove PowerShell, run the following.

$ sudo dnf remove powershell

Install via container

Method 1: Podman container

Podman is an Open Container Initiative (OCI) compliant drop-in replacement for Docker.

Microsoft provides a PowerShell Docker container. The following example will use that container with Podman.

For more information about Podman, visit Podman.io. Fedora Magazine has a tag dedicated to Podman.

To use PowerShell in Podman, run the following script:

$ podman run \
 -it \
 --privileged \
 --rm \
 --name powershell \
 --env-host \
 --net=host --pid=host --ipc=host \
 --volume $HOME:$HOME \
 --volume /:/var/host \
 mcr.microsoft.com/powershell \
 /usr/bin/pwsh -WorkingDirectory $(pwd)

This script creates a Podman container for PowerShell and immediately attaches to it. It also mounts the /home and the host’s root directories into the container so they’re available there. However, the host’s root directory is available in /var/host.

Unfortunately, you can only indirectly run host commands while inside the container. As a workaround, run chroot /var/host to chroot to the root and then run host commands.

To break the command down, everything is mandatory unless specified:

  • -it creates a persistent environment that does not kick you out when you enter it;
  • --privileged gives extended privileges to the container (optional);
  • --rm removes the container when you exit;
  • --name powershell sets the name of the container to powershell;
  • --env-host sets all host environment variables to the container’s variables (optional);
  • --volume $HOME:$HOME mounts the user directory;
  • --volume /:/var/host mounts the root directory to /var/host (optional);
  • --net=host --pid=host --ipc=host runs the process in the host’s namespaces instead of a separate set of namespaces for the contained process;
  • docker.io/microsoft/powershell enters the container;
  • /usr/bin/pwsh -WorkingDirectory $(pwd) enters the container in the current directory (optional).

Optional but very convenient: alias pwsh with the script to easily access the Podman container by typing pwsh.

To remove the PowerShell image, run the following.

$ podman rmi mcr.microsoft.com/powershell

Method 2: Fedora Linux Toolbox container

Toolbox is an elegant solution to setup persistent environments without affecting the host system as a whole. It acts as a wrapper around Podman and takes care of supplying a lot of the flags demonstrated in the previous method. For this reason, Toolbox is a lot easier to use than Podman. It was designed to work for development and debugging. With Toolbox, you can run any command the same as you would directly on the Fedora Workstation host (including dnf).

The installation procedure is similar to the installation on the host methods, with the only difference being that those steps are done inside a container. Make sure you have the toolbox package installed.

Preparing and entering the Fedora 34 Toolbox container is a two step process:

  1. Creating the Fedora 34 Toolbox container
  2. Running the Fedora 34 Toolbox container
$ toolbox create --image registry.fedoraproject.org/f34/fedora-toolbox
$ toolbox enter --container fedora-toolbox

Then, follow the instructions at Method 1: Microsoft repositories.

Optional but very convenient: alias pwsh with toolbox run –container fedora-toolbox pwsh to easily access the Toolbox container by typing pwsh.

To remove the Toolbox container, make certain you have stopped the Toolbox session by entering exit and then run the following:

$ podman kill fedora-toolbox
$ toolbox rm fedora-toolbox
FAQs and Guides Using Software

33 Comments

  1. savemel117

    I use powershell on my fedora from powershell core versione 6.0.

    I manage for my job, two cluster of couchdb servers through PSCouchDB powershell module -> https://github.com/MatteoGuadrini/PSCouchDB on my fedora 34 with powershell 7.1.

    Powershell is a beautiful script language because is Object Oriented Script Language

    • Darvond

      Okay, but why not script in python then?

      To my understanding, python would accomplish this and more, without the cluttered syntax.

      (And that’s ignoring whatever dogmatic issues people may have with Microsoft.)

      • Brian

        Good call on Python, and while it does beat PowerShell in terms of scripting, it doesn’t in terms of shell usage. So, if we are to achieve the similar functionality without PowerShell, we’d be learning and using two different languages. That is, for example, both Bash and Python.

  2. Andre Gompel

    This is just ridiculous !
    The Unix shell, bash being the most popular, are clean, effective, well documented, where the MS-windows Powershell is wordy, clumsy… and only designed to make up for the many weaknesses of Windows.
    By buying and therefor controlling GitHub, MS once again tries to subvert free Open Source Linux. Stay way from this trap !

    • Czocher

      FYI PowerShell has some merits. I agree it is clumsy and doesn’t fit the environment very well, but the advantage it has is it outputs objects instead of strings. This gives a very nice advantage in terms of operating on the return data at a later point. An alternative which fits better with the Linux environment is https://github.com/nushell/nushell . I suggest you have a look, it certainly is interesting.

      • Arouene

        Every programs and commands output strings in Linux. The objects that you can manipulates with PowerShell are only sugar coating translated from the string outputs, on a case by case basis. It means that you are on your own to use outputs that are not translated into objects, like with Get-Process, how do you filter process that are in “Uninterruptible sleep” ? Or others not so common commands ?

        Besides PowerShell is heavy 100Mo per process, and slow.

        For scripting it’s more usefull to use Python, that comes by default on nearly all Linux, and have the avantage to comes with billions libraries that can do anything, and is supported for nearly any ThirdParty services.

      • Brian

        Thanks for suggesting this. It really does seem quite interesting, and it’s even written in Rust!

    • Stendall

      +1

    • There is nothing clumsy or subversive about powershell. It is a bit wordy, but who cares? It’s objects all the way down vs pipes and it’s open source with MIT license. Just like with bash/zsh you just build up aliases or tab completion and flexibility/efficiency comes with muscle memory. Because its objects, it’s pretty self explanatory. Powershell has very robust IDEs that simplify complex actions and for developers who live in .Net (which is open source too) they can use .net Objects from their shell. Pretty powerful. Cool to see this on linux.

    • michael

      sha256sum path/to/file
      vs.
      certUtil -hashfile path/to/file SHA256

      choose your destiny

  3. Joao Rodrigues

    String output is great because it’s simple and every other tool can do string input/output. It’s great that you can use tools like ps, awk, grep, find, etc. and pipe them together.

  4. Darvond

    Okay, so can someone who can actually type lay explain the actual advantages and differences, rather than using a complicated example that seems to be purposefully convoluted and obfuscated?

    For example, the things I like about Bash are the command recall, the plaintext scripting, and the tab completion.

    One also shouldn’t forget the elegance and origins of *sh’s syntax in the deeper Unix roots; there are videos in the AT&T Tech Archive even demonstrating this simplicity by showing the creation of pipelines into programs.

  5. Darvond

    Can someone explain the more practical applications of Powershell in more lay terms?

    Part of the elegance Unix shells is the simplicity in how piped programs can become programs themselves. This is even historically shown to be part of the reason for the existence of shell scripting being the way it is as shown as many historical archives.

    Does Powershell have features comparable to the command recall, tab complete, and plaintext scripting?

  6. Strategist

    My preference is always for bash – simple, clean, elegant and full control. From an Open Source perspective, you need to have full control of the input/process/output. It is the choice of the user to decide what to print. So some tool deciding what would be printable is like controlling your work. OOP better goes with programming and those languages. Things should be sleak and clean. The vast choice of tools is what makes linux and open source the best.

  7. Blackcrack

    Microsoft should be banned from all Linuxdistros !
    Reactos.org should more supportet to have a Clean under GPL2 WindowsNT
    for free around the would and not depended at Microsoft !

    best
    Blacky

  8. Eonfge

    You’re a total mad lad and I really appreciate that. Forget boring Bash or Zsh, use PowerShell! As for the cover image: A+ photoshopping skills… although I’m not sure if a gargantuan turtle blocking the road, is the kind of image that Microsoft was thinking of đŸ˜‰

    +1, will read the rest of the comments in joy

  9. TravelingBavarian

    Great Article! Powershell is at least as good as bash or tcsh. And the comments saying “all other than us are evil” should grab their own nose, cause what you are doing is the same what you are accuse MS. For Example look how good VS Code is in a daily usage for an pro. Forget your stupid politics and religions.
    This article is great and shows what can be done if you need it.

  10. Norbert J.

    Thanks for this amazing article! I also have mixed feelings when Microsoft contributes to the open source ecosystem, but from a technical point of view it looks reasonable to do some things differently from 50 years ago when computers had very limited memory and processing power and were mostly used by specialists.

    What about the legal situation? PowerShell is MIT licensed according to Wikipedia which means it could be provided as regular package in Fedora Linux and other distros?

  11. Frederik

    I am losing more and more respect for Red Hat and Fedora. After IBM bought Red Hat, the commitment to actual freedom is not just reduced, but almost entirely gone.
    The example here is not an apples-to-apples comparison. Instead it is comparing a set of commands that are not part of the shell, that the article tries to compare power shell to, and how they are combined, to builtin functions in power shell.
    At best this is naive and at worst, its a dishonest comparison. Writing functions that work, when combined, equivelantly to the built-in function in powershell is trivial, but will never be part of the shell. Instead it’s proper programmes that are easily combined, because they all have a shared interface.

    The idea that you must know the output of ps is blatantly false and the entire premise for the comparison is broken. As the article points out, all you have to know, is that $2 exists and has the value you want. The same is true in the power shell example, where you must know that what WorkingSet is and how you can compare it to something.

    • I’m not able to see what impact using PowerShell on Fedora Linux has on your freedom or what the RedHat/IBM transaction had to do with the ability to use an MIT Licensed tool.

      We all have opinions but I think it best to stick with the technology in this forum.

      But thanks for being part of the conversation.

      • Frederik

        It’s not the first time that Fedora Magazine has advocated using software that originates in organizations that are fighting free software. If you think free software is about technology, I think you’re missing the entire point of technology.

        • There is no advocating for software in the Fedora Magazine. The articles are written by volunteers to provide information and introduce software and techniques that Fedora Linux users might find interesting and/or helpful.
          This ends my involvement in this discussion.

    • Alright, let me be clear here.

      Red Hat and IBM have nothing to do with this post. The authors of this article, Ozymandias42 and I, are not even affiliated with Red Hat or IBM; we never worked at Red Hat or IBM, we don’t pay for their services, etc. We felt like working together to write an article about PowerShell, so we did.

      • Frederik

        Nobody is saying you are. Nobody hinted or suggested that you are. These kinds of articles are just becoming more and more common on Fedora magazine. You write whatever article you feel like writing and publish them wherever you feel like publishing. The bulk of the comment was about how the comparison was dishonest, but for some reason that part has not been commented on at all.

        • Brian

          Your comment was that Red Hat and Fedora’s commitment to freedom was gone because Red Hat was purchased by IBM. You most CERTAINLY implied that Red Hat and IBM had something to do with this article. Otherwise, there would not be any point in mentioning it.

          If you think an MIT-licensed shell is not free software, then I don’t know what to tell you.

  12. G Fernandes

    If you really love objects all that much, simply script in Python.

  13. Daichi

    On my intern days, I had just learned about Linux and Fedora (I was a Windows only user) and started writing Bash scripts to help managing the few Linux servers on the company I work for.

    The number of Linux servers grew and I was already confident on Bash. Microsoft had just released the first versions of Powershell, but only later I found out how useful it was to automatize processes on Windows, much like bash was on Linux.
    After getting used to it too, sometimes when I went back to Bash, I felt that the object manipulation was really handy in some occasions.
    That’s when I started learning some Python.

    Powershell has all the merits it deserve on Windows, maybe it came a bit late to Linux, but it’s good to know it’s supported on Fedora.

    Maybe some idea for the next article be performance comparisons to Bash and Python?

  14. PowerShell on linux? Sounds like you hit the proverbial jackpot with windows v linux. I enjoyed the article and this solves an issue for me. I’ve been interested in learning PowerShell but didn’t want to boot into windows to do it. Thank you

  15. Fenyx

    Thanks for writing a nice introduction to Powershell. While it seems odd at first, it’s very powerful being able to pipe full objects rather than just text.

    One small correction in the alias for pwsh you have “toolbox run –container fedora-toolbox pwsh” and it should be “toolbox run –container fedora-toolbox pwsh”. Probably caused by a text editor trying to help!

    I look forward to more in this series.

  16. Stephen Snow

    Powershell has it’s place on Windows where it is the only way to get some critical things accomplished, like rescuing a corrupted installation of Win10 for instance. I use it there quite often, and am thankful for MS dev’s, and users releasing some of their toolkit for general use. As for Linux, and my Fedora Linux Silverblue box, I don’t need Powershell, so I won’t be installing it, much like I won’t ever use their coding studio. That is more than a personal preference of software to use for my purposes, which due to the mere ubiquity, would go much smoother using closed source products, such as MS provides. It comes down to a personal choice to foregoe the ease of use trap, in favour of support for the Open Source alternatives already available either directly or indirectly. That is not to say the FOSS alternatives are less easy to use, just not as well known in most cases.
    This openness of community that we are witnessing here, BTW is also why I read Fedora Magazine and have for a number of years. Ideas we talk about, even those we find controversial, can still be discussed openly.
    So I, won’t be putting MS products onto my Fedora Linux box, but others are welcome to do so if that floats their boat’s (fit’s their needs). I won’t judge, but I will likely point out the FOSS alternatives, and why they are more suited to use.
    Has anyone (else) bothered to notice the following (which I ripped from an Open Source Highlights article) “Linux inherited a lot from Unix, which has been around for a half-century. This means most of the tools you use in your Linux terminal probably either have a very long history or were written to emulate those historical commands. It’s a point of pride in the POSIX world that tools don’t need constant reinvention. In fact, there’s a subset of Linux users today who could run a version of Linux from before they were born without having to learn anything new. It’s tried, true, and reliable.” The full article can be read at https://opensource.com/article/21/7/rust-tools-linux?utm_medium=Email&utm_campaign=weekly&sc_cid=7013a000002wQ7rAAE

Comments are Closed

The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat. Fedora Magazine aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. The Fedora logo is a trademark of Red Hat, Inc. Terms and Conditions