gpt4 book ai didi

windows - 如何获取 Powershell 中的 CPU 内核数?

转载 作者:行者123 更新时间:2023-12-05 01:06:03 24 4
gpt4 key购买 nike

假设我在 Windows 机器上运行(电源)shell。

有没有我可以使用的单线:

  1. 物理处理器内核的数量和/或
  2. 运行中线程的最大数量,即核心 * 超线程因子?

注意:我只想要一个数字作为命令输出,而不是任何标题或文本。

最佳答案

Ran Turner's answer提供了关键指针,但可以通过两种方式改进:

  • CIM cmdlet(例如,Get-CimInstance)取代了 PowerShell v3(2012 年 9 月发布)中的 WMI cmdlet(例如,Get-WmiObject)。因此,应该避免使用 WMI cmdlet,尤其是因为 PowerShell (Core) (v6+),所有 future 的努力都将用于,甚至不再拥有它们。但是请注意,WMI 仍然是 CIM cmdlet 的基础。如需更多信息,请参阅 this answer .

  • Format-Table与所有 Format-* cmdlet 一样,旨在为人类观察者生成用于显示的格式,而 em> 输出适合以后程序化处理的数据(参见this answer了解更多信息)。

    • 要改为使用输入对象属性的 子集 创建 对象,请使用 Select-Object cmdlet。 (如果输出对象具有 4 个或更少的属性并且未被捕获,则它们隐式格式化为好像 Format-Table 已被调用;具有 5 个或更多属性, 是隐含的Format-List)。

因此:

# Creates a [pscustomobject] instance with 
# .NumberOfCores and .NumberOfLogicalProcessors properties.
$cpuInfo =
Get-CimInstance –ClassName Win32_Processor |
Select-Object -Property NumberOfCores, NumberOfLogicalProcessors

# Save the values of interest in distinct variables, using a multi-assignment.
# Of course, you can also use the property values directly.
$cpuPhysicalCount, $cpuLogicalCount = $cpuInfo.NumberOfCores, $cpuInfo.NumberOfLogicalProcessors

当然,如果您只对 values 感兴趣(CPU 仅计算为数字),则不需要 intermediate 对象并且可以省略 Select-Object 上面调用。

至于单线:

如果您想要一个创建不同变量的单行程序,而无需重复 - 昂贵的 - Get-CimInstance 调用,您可以使用 aux。利用 PowerShell 将赋值用作表达式的能力的变量:

$cpuPhysicalCount, $cpuLogicalCount = ($cpuInfo = Get-CimInstance -ClassName Win32_Processor).NumberOfCores, $cpuInfo.NumberOfLogicalProcessors
  • 要将数字保存在不同的变量中输出它们(将它们作为 2 元素数组返回),请将整个语句括在 (...).

  • 输出数字,只需省略$cpuPhysicalCount, $cpuLogicalCount =部分即可。

关于windows - 如何获取 Powershell 中的 CPU 内核数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69868053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com