之前尝试过使用系统的性能计数器组件(ManagementObjectSearcher)来获取,但发现很多新装的服务器没没有安装对应组件,偶然发现用powershell.exe来执行也是可以的,而且用虚拟机测试win7到win2016基本都预装了而且使用中也没有发现问题 于是就采用了这个方案,唯一的缺点就是每次都要启动一次powershell.exe,速度相对会慢一些。
接下来我们就可以通过System.Diagnostics.Process类执行PowerShell.exe来执行脚本以此来获取cpu温度。
以下是使用C#与PowerShell获取CPU温度的示例代码
首先,需要导入System.Diagnostics命名空间,该命名空间提供了与进程相关的类和方法。
using System; using System.Diagnostics; namespace CpuTemperatureExample { class Program { static void Main(string[] args) { try { string powerShellScript = @" $temp = Get-WmiObject -Namespace 'root\\WMI' -Class MSAcpi_ThermalZoneTemperature | Select-Object -ExpandProperty CurrentTemperature $temp = ($temp - 2732) / 10.0 Write-Output $temp "; ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = "powershell.exe"; psi.Arguments = "-ExecutionPolicy ByPass -Command " + powerShellScript; psi.RedirectStandardOutput = true; psi.UseShellExecute = false; psi.CreateNoWindow = true; using (Process process = Process.Start(psi)) { string output = process.StandardOutput.ReadToEnd(); double temperature = Convert.ToDouble(output); Console.WriteLine("CPU温度: " + temperature + "°C"); } } catch (Exception e) { Console.WriteLine("获取CPU温度时发生错误: " + e.Message); } Console.ReadLine(); } } }
在上面代码中,使用Get-WmiObject命令获取MSAcpi_ThermalZoneTemperature类的实例,并计算并输出CPU温度。
使用ProcessStartInfo配置powershell.exe进程,并指定执行PowerShell脚本的参数。
使用Process类启动PowerShell进程,并从进程输出中读取CPU温度值,然后输出到控制台。
请注意,这种方法需要系统中安装有PowerShell,并且需要适当的权限来执行PowerShell脚本。在某些情况下,可能需要在psi.FileName中指定完整的PowerShell可执行文件路径。