How do I get the localhost (machine) name in PowerShell? I am using PowerShell 1.0.
You can just use the .NET Framework method:
[System.Net.Dns]::GetHostName()
also
$env:COMPUTERNAME
Don't forget that all your old console utilities work just fine in PowerShell:
PS> hostname
KEITH1
$name = $(hostname)
Long form:
get-content env:computername
Short form:
gc env:computername
computername
is the NetBIOS name, which is limited to 15 characters.
All above questions are correct but if you want the hostname and domain name try this:
[System.Net.DNS]::GetHostByName('').HostName
A slight tweak on @CPU-100's answer, for the local FQDN:
[System.Net.DNS]::GetHostByName($Null).HostName
In PowerShell Core v6 (works on macOS, Linux and Windows):
[Environment]::MachineName
hostname
also works just fine in Powershell
An analogue of the bat file code in Powershell
Cmd
wmic path Win32_ComputerSystem get Name
Powershell
Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name
and ...
hostname.exe
The most descriptive way for me is:
[System.Net.DNS]::GetHostByName($env:COMPUTERNAME).HostName
You can store the value as follows $name = $(hostname)
I want to add that simply executing $name = hostname
will also save the localhost name of the PC into a variable.
Not specifically for Powershell version 1.0 and more of an overview of different possible ways to get information via Powershell:
Native CmdLet (usually the best, but sadly really slow to get the Computername): (Get-ComputerInfo).CsDNSHostName Returns the "Name of local computer according to the domain name server" (Info about Get-ComputerInfo, Info about its return value)
Classical CommandLine executable: hostname.exe Returns the "host name portion of the full computer name of the computer" (Info about hostname.exe
Environment Variable: $env:COMPUTERNAME
Registry: (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName).ComputerName
Static .Net Property: [Environment]::MachineName Returns "the NetBIOS name of this local computer." (Info about the System.Environment class)
Property of COM-Object (Computername via deprecated Scripting-Api): (New-Object -ComObject WScript.Network).ComputerName Returns "the name of the computer system." (Info about the WshNetwork Object, Info about the Windows Script Host Objects)
Property of WMI-Object: (Get-CimInstance -ClassName Win32_ComputerSystem).Name (Info about Win32_ComputerSystem)
Success story sharing
[System.Net.Dns]::GetHostName()
(doesn't truncate) is better than$env:COMPUTERNAME
(truncates)$env:COMPUTERNAME
works fine on Windows 10 (please note dollar sign at the beginning)$env:COMPUTERNAME
won't work on Linux and macOS. However,[Environment]::MachineName
does.