You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell获取域内远程计算机的操作系统名称

PowerShell查询域内远程设备操作系统名称方案

前置要求

  • 你的域账户拥有目标设备的合法访问权限
  • 目标Windows设备默认开启WinRM即可,目标Linux设备需开启WinRM服务或SSH服务

方案1:仅查询域内Windows设备(速度最快,无额外配置)

直接调用CIM命令获取Windows设备OS信息,域内权限足够即可直接执行:
Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName 目标主机名 | Select-Object @{Name='主机名';Expression={$_.CSName}},@{Name='操作系统';Expression={$_.Caption}},@{Name='版本号';Expression={$_.Version}}

方案2:跨平台批量查询(支持Windows/加域Linux设备)

适用于已在Linux设备上安装PowerShell 7+并配置WinRM远程的场景,可自动识别系统类型返回对应信息:

# 填入需要查询的主机列表
$targetHosts = @("PC001","PC002","LinuxSVR01")

Invoke-Command -ComputerName $targetHosts -ScriptBlock {
    if ($IsWindows) {
        $osInfo = Get-CimInstance Win32_OperatingSystem
        return [PSCustomObject]@{
            操作系统 = $osInfo.Caption
            版本号 = $osInfo.Version
        }
    }
    elseif ($IsLinux) {
        $osName = if (Test-Path /etc/os-release) {
            (. /etc/os-release; $PRETTY_NAME)
        }
        else {
            lsb_release -d | cut -f 2
        }
        $kernelVer = uname -r
        return [PSCustomObject]@{
            操作系统 = $osName
            版本号 = $kernelVer
        }
    }
} | Select-Object @{Name='主机名';Expression={$_.PSComputerName}},操作系统,版本号

方案3:Linux未装PowerShell场景的兼容方案

如果目标Linux设备没有安装PowerShell,可优先走CIM查Windows,失败自动走SSH查询Linux信息:

$targetHosts = @("PC001","PC002","LinuxSVR01")

foreach ($host in $targetHosts) {
    $result = [PSCustomObject]@{
        主机名 = $host
        操作系统 = "查询失败"
        版本号 = "N/A"
    }
    # 优先查询Windows设备
    try {
        $cimRes = Get-CimInstance Win32_OperatingSystem -ComputerName $host -ErrorAction Stop
        $result.操作系统 = $cimRes.Caption
        $result.版本号 = $cimRes.Version
        $result
        continue
    }
    catch {}
    # CIM查询失败走SSH查询Linux
    try {
        $sshRes = Invoke-Command -HostName $host -ScriptBlock {
            $os = if (Test-Path /etc/os-release) { (. /etc/os-release; $PRETTY_NAME) } else { uname -s }
            $ver = uname -r
            return "$os||$ver"
        } -ErrorAction Stop
        $result.操作系统 = $sshRes.Split("||")[0].Trim()
        $result.版本号 = $sshRes.Split("||")[1].Trim()
    }
    catch {}
    $result
}

注意事项

  • 查询大量设备时可给对应命令添加超时参数,避免单台设备离线导致脚本卡住
  • 未加入域的设备需要单独配置信任列表或认证信息才可正常查询
  • Linux设备如果配置了域账户SSH认证,可直接使用当前域账户执行查询,无需额外输入密码

内容的提问来源于stack exchange,提问作者Nicolò Vitelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:06:03