How do I get the localhost name in PowerShell?
.NetPowershell.Net Problem Overview
How do I get the localhost (machine) name in PowerShell? I am using PowerShell 1.0.
.Net Solutions
Solution 1 - .Net
You can just use the .NET Framework method:
[System.Net.Dns]::GetHostName()
also
$env:COMPUTERNAME
Solution 2 - .Net
Don't forget that all your old console utilities work just fine in PowerShell:
PS> hostname
KEITH1
Solution 3 - .Net
Long form:
get-content env:computername
Short form:
gc env:computername
Solution 4 - .Net
All above questions are correct but if you want the hostname and domain name try this:
[System.Net.DNS]::GetHostByName('').HostName
Solution 5 - .Net
A slight tweak on @CPU-100's answer, for the local FQDN:
[System.Net.DNS]::GetHostByName($Null).HostName
Solution 6 - .Net
In PowerShell Core v6 (works on macOS, Linux and Windows):
[Environment]::MachineName
Solution 7 - .Net
hostname
also works just fine in Powershell
Solution 8 - .Net
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
Solution 9 - .Net
The most descriptive way for me is:
[System.Net.DNS]::GetHostByName($env:COMPUTERNAME).HostName
Solution 10 - .Net
> 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.