In PowerShell Core, there are three useful variable you can use in a cross-platform scripts. Then, the script can have the necessary logic to response based on the environment it is running.
Use the cmdlet Get-Variable to find them, and keep in mind, these variables are not found in Windows PowerShell 5.x.
Although, the results will display four variable, but let’s pay attention to three of them. Below are the variables with their default values:
These three variables can help in identifying which Operating System the script are been executed. This way just adding the necessary logic, in order to take the correct action.
For example, you can want to execute a Python code on different systems.
In Windows, if Anaconda (Python 3.6) was installed then Python executable is located at: C:\ProgramData\Anaconda3\python.exe
In Ubuntu Linux, Anaconda (Python 3.6) may be found on user Home folder, then it can be located at: /home/username/anaconda3/bin/python
Of course, Python location may vary if different versions are installed, and/or installation default location was change.
Sample Cross-platform Code Snippet
Here’s a simple script code logic to accomplished cross-platform behavior. In my environment the sample code was executes in a Windows system.
if ($IsLinux -eq $true)
Write-Host “Executing in Linux – $($psversionTable.platform.ToString())” -ForegroundColor Green;
#Linux Python path:
if ((Test-Path ‘/home/maxt/anaconda3/bin/python’) -eq $true)
Write-Host “Linux Python Path Validated” -ForegroundColor Yellow;
if ($IsWindows -eq $true)
Write-Host “Executing in Windows – $($psversionTable.platform.ToString())” -ForegroundColor Green;
#Windows Python path:
if ((Test-Path ‘C:\ProgramData\Anaconda3\python.exe’) -eq $true)
Write-Host “Windows Python Path Validated” -ForegroundColor Yellow;
Write-Host “Can’t execute under this OS!”;
Go ahead and try the same code in Linux PowerShell Core. Of course, this code can be improved, but let’s leave it to your creativity. Start simple and grow!
By the way, did you know you can use SAPIEN Technologies PrimalScript to execute PowerShell Core scripts. Yes! It is possible!
Check the following SAPIEN Blog post about it: https://www.sapien.com/blog/2017/09/15/using-powershell-core-in-primalscript/