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
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
See you next time with PowerShell!
Categories: PowerShell
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
LikeLike
Thank you. Will correct it!
LikeLike
What version of PS is this tied to? I just tried it on my Windows 10 machine and it came back with nothing.
LikeLike
PowerShell 7
LikeLike
Is there a method to determine this remotely?
LikeLike
Yes. Just look at my downloads section and you will find what you are looking for.
LikeLike
What about determining the OS type remotely?
LikeLike