当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 获取计算机名称和域

作者:精品下载站 日期:2024-12-15 00:28:55 浏览:15 分类:玩电脑

使用 PowerShell 获取计算机名称和域


PowerShell 提供了一种快速获取计算机名称和其他信息(例如本地计算机的域名)的方法。在这篇博文中,我将向您解释使用不同的 PowerShell cmdlet 获取本地计算机主机名的最佳方法。

让我们尝试使用下面的 PowerShell cmdlet 来获取计算机名称和域名。

PowerShell 获取计算机名称和域

您可以使用 PowerShell 中提供的不同命令获取计算机名称,如下所示

  • 主机名.exe
  • WMI
  • 环境变量
  • .Net 机器名
  • .Net 获取主机名

让我们检查 PowerShell 以使用上述选项获取计算机名称。

使用 HostName.exe 获取计算机名称

HostName.exe 是计算机驱动器上可用的可执行文件,应位于 C:\Windows\System32HostName.exe 包含机器代码和命令。

PS C:\>HostName.exe

在上面的命令中,HostName.exe 获取 PowerShell 中的计算机名称或主机名。

注意:您可以在命令提示符下运行 HostName.exe 命令来获取 PowerShell 中的计算机名称。

酷提示:如何在 PowerShell 中使用 Get-AdDomainController 获取域控制器!

使用WMI获取计算机名称

WMI(Windows Management Instrumentation)用于在标准环境中访问管理信息。 WMI 使用 CIM(通用信息模型)标准来表示系统、应用程序、设备、网络等。

使用 PowerShell Get-WMIObject cmdlet,它可以提取有关 WMI 类实例的信息以及有关可用类的信息

#Get Computer system information
Get-WMIObject Win32_ComputerSystem

#Get Computer name from available System information
Get-WMIObject Win32_ComputerSystem| Select-Object -ExpandProperty Name

#Get Domain name from available System Information
Get-WMIObject Win32_ComputerSystem| Select-Object -ExpandProperty Domain

第一个命令返回有关计算机系统的信息,例如获取计算机名称、域名、制造商、获取计算机型号等。

第二个命令,Get-WMIObject Win32_ComputerSystem| Select-Object -ExpandProperty Name 使用管道运算符通过早期命令输出获取计算机名称。

第三个命令使用 PowerShell 获取域名。

使用 CIM 获取计算机名称

您可以使用PowerShell Get-CIMInstance 访问通用信息模型并返回有关计算机系统的信息

# Get computer information
Get-CIMInstance CIM_ComputerSystem

#Get Computer name only from available system information
(Get-CIMInstance CIM_ComputerSystem).Name

上面的命令返回计算机系统详细信息,例如名称、PrimaryOwnerName、域名、计算机型号、制造商等等。由于我们只需要主机名,因此在 PowerShell 中使用 Name 获取计算机名称。

使用环境变量获取主机名

PowerShell 中获取主机名的一个非常简单的方法是使用环境变量。使用 $env 获取计算机名称

$env:computername

使用 .Net 机器名称

您可以在 PowerShell 中轻松使用 .Net。借助.Net类,您可以轻松获取机器名称。

[system.environment]::MachineName

使用 .Net GetHostName() 函数

如上所述,可以在 PowerShell 中轻松访问 .Net。您可以使用 .net 提供的类 System.Net.Dns 来使用 GetHostName() 函数获取主机名。

[System.Net.Dns]::GetHostName()

酷提示:您知道 Windows 中的 cat 等效命令吗?

结论

在本文中,我们介绍了使用 PowerShell 获取计算机名称或域名的不同方法。

我希望您发现上述示例有助于使用 PowerShell 获取主机名或域名。

请阅读此处,使用 PowerShell 检查计算机是否是域或工作组的成员。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯