Tinus EngOps Wiki

Logo

OpsaC - Operating as PowerShell code

Links

Home

PowerShell Blog

PowerShell Index

PowerShell Search

Additional Websites

View my GitHub Profile

View my GitHub Gists

View Tinus IT Wiki

View my Photo Website

How to get the current OS

tags: PowerShell categories: PowerShell-Basic

Table of Contents

PowerShell 7

With PowerShell 7 it’s easy to determine the current os:

$IsMacOS
$IsLinux
$IsWindows

Windows PowerShell

In Windows PowerShell it’s easy to determine the current os:

[Environment]::OSVersion

Unknown Environment

If you don’t know which PowerShell you running on which OS, you can use the following code:

# define an enumerator for the OS-type
enum OSType {
    Linux
    Mac
    Windows
}

function Get-CurrentOS {
    # if the PSVersion is less than 6, it's Windows PowerShell
    if($PSVersionTable.PSVersion.Major -lt 6){
        return [OSType]::Windows
    }
    # if the PSVersion is greather than 6, you can use the pwsh constants
    else{
        if($IsMacOS)   {return [OSType]::Mac}
        if($IsLinux)   {return [OSType]::Linux}
        if($IsWindows) {return [OSType]::Windows} 
    }
}

switch(Get-CurrentOS){
    Mac {
        $OSVersion = "$(sw_vers -productName) $(sw_vers -productVersion).$(sw_vers -buildVersion)"
        Write-Host "Running on $($OSVersion)" -ForegroundColor Cyan
    }
    Linux {
        $OSVersion = $((Get-Content /etc/*release | Select-String -Pattern 'DISTRIB_DESCRIPTION=') -replace 'DISTRIB_DESCRIPTION=')
        Write-Host "Running on $($OSVersion)" -ForegroundColor Cyan
    }
    Windows {
        $OSVersion = "$((Get-CimInstance -ClassName Win32_OperatingSystem).Caption) ($([System.Environment]::OSVersion.Version.ToString()))"
        Write-Host "Running on $($OSVersion)" -ForegroundColor Cyan
    }
}

See also

Determine the OS version, Linux and Windows from Powershell on stack overflow

[ Top ] [ Blog ]