Determine the OS version, Linux and Windows from Powershell

boomcubist picture boomcubist · Jun 22, 2017 · Viewed 25.4k times · Source

How can I determine the OS type, (Linux, Windows) using Powershell from within a script?

The ResponseUri isn't recognised when this part of my script is ran on a Linux host.

$UrlAuthority = $Request.BaseResponse | Select-Object -ExpandProperty ResponseUri | Select-Object -ExpandProperty Authority

So I want an If statement to determine the OS type that would look similar to this:

If ($OsType -eq "Linux")
{
     $UrlAuthority = ($Request.BaseResponse).RequestMessage | Select-Object -ExpandProperty RequestUri | Select-Object -ExpandProperty host
}
Else
     $UrlAuthority = $Request.BaseResponse | Select-Object -ExpandProperty ResponseUri | Select-Object -ExpandProperty Authority

I could use Get-CimInstance Win32_OperatingSystem but it would fail on Linux as it's not recognised.

Answer

Maximilian Burszley picture Maximilian Burszley · Jun 22, 2017

Aren't there environment variables you can view on the other platforms for the OS?

Get-ChildItem -Path Env:

Particularly, on Windows at least, there's an OS environment variable, so you should be able to accomplish this by using $Env:OS.


Since some time has passed and the PowerShell Core (v6) product is GA now (the Core branding has been dropped as of v7), you can more accurately determine your platform based on the following automatic boolean variables:

$IsMacOS
$IsLinux
$IsWindows