Search code examples
powershellunameplatform-detection

How to detect Linux or macOS or Windows in powershell?


I use uname -s in bash scripts to determine the OS and it returns Linux, Darwin or MINGW64_NT... when its running on Linux, macOS or Windows.

EDIT0 : I want my $PROFILE script to detect the OS whether is running on Windows with PS (version could be lower than 6) or Linux with PSv>=6.

I found this in powershell :

PS> [System.Environment]::OSVersion.Platform

On Linux, it returns Unix and on a 64bits Windows, it returns Win32NT.

I don't have a macOS at my disposal (not yet:)) so I don't know what it actually returns on macOS.

EDIT1 : This method doesn't seem to different between Unix and Linux or Windows32b and Windows64b.

What other ways are there to detect the OS in powershell 5.1 ?


Solution

  • The problem is Powershell 5.1.

    Detailed Here: https://devblogs.microsoft.com/scripting/powertip-determine-your-version-of-powershell-and-host-operating-system/

    More Detail Here: Determine the OS version, Linux and Windows from Powershell

    Powershell 5.1 does not have the capacity nor ability to determine OS outside of the Microsoft environment. The best you can do is, using get-wmi or cim-sesssion

     windows 
     !windows
    

    For PowerShell Core (Powershell Version 6.0+), you can use Automatic Variables:

    $IsLinux
    $IsMacOS
    $IsWindows
    

    With 6+ you can do something to the effect of:

       foreach ($i in $info) {
        
        if ($i -eq $IsLinux) {
            Write-Host $i is Linux
        }
        elseif ($i -eq $IsMacOS) {
            Write-Host $i is This is a dirty, dirty Mac
        }
        elseif ($i -eq $IsWindows) {
            Write-Host $i is Windows
        }
    
       }
    

    To bring this to a close what you are asking for is simply not possible / possibly not worth the effort with PowerShell 5.1.