PowerShell

PowerShell: Determining Operating System with $IsWindows, $IsLinux and $IsMacOs

Recently, I discovered three PowerShell Core variables that could be very helpful when it comes to determining the operating system in PowerShell. PowerShell has become a cross-platfrom tool and can be installed on Linux or MacOs, too. So it could happen that you have to determine the operating system first before starting any other actions.

$IsWindows, $IsLinux, $IsMacOS

What I am talking about are these three PowerShell variables shipped with PowerShell Core 6 and PowerShell 7:


$IsLinux

$IsMacOS

$IsWindows

1.PNG

What can we do with it? For instance, if you want to implement a PowerShell script, it could make sense to determine the computers installed operating system first.

Here’s an example script that determines if the system is running Windows. The code is stored in $testos.


$testos = { If ($IsWindows)
{
Write-Warning 'System is running Windows. Script started.'
}
else
{
throw 'System is not Windows. Operation aborted.'
}
}

My local computer is running Windows, therefore the imaginary script would be executed.


&$testos

1.PNG

See you next time with PowerShell!

Categories: PowerShell

Tagged as: ,

8 replies »

  1. Patrick:

    A bit of typo

    $IsWinodws, $IsLinux, $IsMacOS

    Should read

    $IsWindows, $IsLinux, $IsMacOS

    Very nice content.

    Thanks for placing so much of your hard work in the public domain.

    May God reward you

    Daniel Adeniji

    Like

  2. What version of PS is this tied to? I just tried it on my Windows 10 machine and it came back with nothing.

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.