Determining Your Platform

by Jan 18, 2022

PowerShell today is cross-platform so even though you may still use Windows PowerShell on Windows servers, your scripts may well end up running on different operating systems.

If your script wants to know the platform it is running on, in a backward-compatible way, try these lines:

$RunOnWindows = (-not (Get-Variable -Name IsWindows -ErrorAction Ignore)) -or $IsWindows
$RunOnLinux = (Get-Variable -Name IsLinux -ErrorAction Ignore) -and $IsLinux
$RunOnMacOS = (Get-Variable -Name IsMacOS -ErrorAction Ignore) -and $IsMacOS

Get-Variable -Name RunOn*

On a Windows system, the result looks like this:

 
Name                           Value
----                           -----
RunOnLinux                     False
RunOnMacOS                     False 
RunOnWindows                   True
 

You can now safely check prerequisites and make sure your script code runs only where appropriate.


Twitter This Tip! ReTweet this Tip!