You can run a PowerShell script from the Bash through two steps:
- Step 1: Install PowerShell core in your system,
- Step 2: Execute your PowerShell script using the core handle
We will test the ideas using the following bash emulations: the Tilix terminal on Debian (for Linux), Mac Terminal, and Git Bash on Windows
Step 1: Installing PowerShell Core
For Linux/ Debian Users
You can install PowerShell core on Debian by running the following commands from the terminal (source: Microsoft website).
1 2 3 4 5 6 7 8 |
# Install system components sudo apt update && sudo apt install -y curl gnupg apt-transport-https # Import the public repository GPG keys curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - # Register the Microsoft Product feed sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-bullseye-prod bullseye main" > /etc/apt/sources.list.d/microsoft.list' # Install PowerShell sudo apt update && sudo apt install -y powershell |
If you use a different distro, please get the installation commands here.
Note: After the installation, you may find PowerShell on the apps list, but you may not be able to launch it by clicking it (Go to Step 2).
For Windows Users
You probably have PowerShell installed on your system. If not, or if you want to update, use this link.
If you want to use Bash on Windows, a good BASH emulation app is Git for Windows, which can be downloaded from https://gitforwindows.org/.
For Mac Users
You can install PowerShell core by using Homebrew by running the following command.
1 |
brew install --cask powershell |
Or update it using the commands
1 2 |
brew update brew upgrade powershell --cask |
Note: After installing PowerShell, you may see the app on the apps list, but you may not be able to launch it by clicking on the icon. If you click the icon, an instance of PowerShell will be launched from the Mac Terminal.
Step 2: Launching PowerShell Core and Using it to Execute a PowerShell Script.
You can launch the PowerShell core from Linux Terminal, Git Bash for Windows, or Mac Terminal using the command:
1 |
pwsh |
And you can execute a PowerShell script using the command
1 |
pwsh <path_to_the_PowerShell_script> |
Let’s try that by running the script below. The script accepts one parameter, $Name, then prints a message based on the time of the day.
Scrip Name: script1.ps1
1 2 3 4 5 6 7 8 9 10 11 |
param( $Name ) $noon = Get-Date -Hour 12 -Minute 0 -Second 0 $current_time = Get-Date Write-Host "The time is $current_time" if ($current_time -gt $noon){ Write-Host "Good afternoon, $Name`!" } else { Wite-Host "Good morning, $Name`!" } |
On Debian Tilix Terminal:
On Git Bash for Windows:
On Mac Terminal:
Conclusion
Running PowerShell from Bash boils down to installing the PowerShell core and using the core handle to run PowerShell scripts. In this article, we covered how to install PowerShell on different platforms and how to use it to run a PowerShell script.