Determine the OS version, Linux and Windows from Powershell
Solution 1
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
Solution 2
For PowerShell Core (Powershell Version 6.0+), you can use Automatic Variables: $IsLinux
, $IsMacOS
and $IsWindows
.
For example,
if ($IsLinux) {
Write-Host "Linux"
}
elseif ($IsMacOS) {
Write-Host "macOS"
}
elseif ($IsWindows) {
Write-Host "Windows"
}
Solution 3
Actually, there should be global variables added by the PowerShell console itself--they're not considered environment variables though, which is why they wouldn't show up when using dir env:
to get a list.The OS-specific ones I see for now are $IsLinux
, IsMacOS
and $IsWindows
. This is of at least PowerShell version 6.0.0-rc and above for Mac/Linux.
You can see a list of what's available by using just Get-Variable
(in a fresh session without loading your profile, if you just want what comes build-in by default).
Solution 4
Building on the above, if you only want to detect whether or not you're running under Windows, and you want a script that's forwards and backwards compatible in PowerShell and PowerShell Core, there's this:
if ($IsWindows -or $ENV:OS) {
Write-Host "Windows"
} else {
Write-Host "Not Windows"
}
Solution 5
When you only have to check if it is windows or linux, maybe you could use this (quick and dirty):
if ([System.Boolean](Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue))
{
#windows
}
else
{
#Not windows
}
Comments
-
boomcubist over 2 years
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.