linux - 从 Powershell 确定操作系统版本、Linux 和 Windows

标签 linux windows powershell operating-system powershell-core

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

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

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

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

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 上会失败,因为它无法被识别。

最佳答案

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

Get-ChildItem -Path Env:

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


由于一段时间过去了,PowerShell Core (v6) 产品现已正式发布(Core 品牌已从 v7 开始删除),您可以更准确地确定您的平台基于以下自动 bool 变量:

$IsMacOS
$IsLinux
$IsWindows

关于linux - 从 Powershell 确定操作系统版本、Linux 和 Windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44703646/

相关文章:

linux - 将 gensub 应用于 awk 中所有字段的快捷方式

c - 如何初始化包含 union 数组的结构

linux - 从驱动程序到应用程序的信号处理

python - 使用批处理将文件和文件夹复制到另一个路径

使用system2()而不是system()从R运行Powershell脚本

linux - 如何导出 lxc 容器?

windows - TNS 端口在 Oracle 11g 快捷版安装问题中不可用

windows - 安装 ruby​​ gem 时出错

sql-server - SQL Powershell错误: Invoke-Sqlcmd : The term 'Invoke-Sqlcmd' is not recognized as the name of a cmdlet

powershell - 跳转到 PowerShell 脚本中的另一部分