从 Powershell 确定操作系统版本、Linux 和 Windows [英] Determine the OS version, Linux and Windows from Powershell

查看:21
本文介绍了从 Powershell 确定操作系统版本、Linux 和 Windows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在脚本中使用 Powershell 确定操作系统类型(Linux、Windows)?

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

当我的这部分脚本在 Linux 主机上运行时,无法识别 ResponseUri.

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

所以我想要一个 If 语句来确定类似于此的操作系统类型:

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

我可以使用 Get-CimInstance Win32_OperatingSystem 但它在 Linux 上会失败,因为它无法被识别.

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

推荐答案

操作系统的其他平台上没有可以查看的环境变量吗?

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

Get-ChildItem -Path Env:

特别是,至少在 Windows 上,有一个操作系统环境变量,因此您应该能够通过使用 $Env:OS 来完成此操作.

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

由于一段时间过去了,PowerShell Core (v6) 产品现在是 GA(Core 品牌已从 v7 中删除),您可以更准确地确定您的平台基于以下自动布尔变量:

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

这篇关于从 Powershell 确定操作系统版本、Linux 和 Windows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆