Writing PowerShell Scripts in Linux

You can administer Linux with PowerShell and run scripts with what you already know from using it in Windows.

Install PowerShell in Linux

Installation is done with one line:

sudo snap install powershell --classic

Once installed, run powershell from the command line to test if it works. You can quit PowerShell and return to the default Linux shell by typing exit.

Hello World Script

Before you write the script, you need to know which path PowerShell is installed. The path to the interpreter needs to be in the script in order for it to run. You can find the location of PowerShell with:

which powershell

This typically returns

/snap/bin/powershell

This path is added to the script with the shebang (#!). Below is a simple “hello world” script with the message in Latin to make you look more clever.

helloworld.ps1
============

#! /snap/bin/powershell
Write-Host "Salve mundi!"

After you save the script, you need to give it execute permissions in order for it to run in Linux. This is done with

chmod +x helloworld.ps1

Once this is done, you can then run it the default shell or within PowerShell by typing

./helloworld.ps1

Leave a Comment