199
votes

How do I get the localhost (machine) name in PowerShell? I am using PowerShell 1.0.

9

9 Answers

287
votes

You can just use the .NET Framework method:

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

also

$env:COMPUTERNAME

67
votes

Don't forget that all your old console utilities work just fine in PowerShell:

PS> hostname
KEITH1
39
votes

Long form:

get-content env:computername

Short form:

gc env:computername
17
votes

All above questions are correct but if you want the hostname and domain name try this:

 [System.Net.DNS]::GetHostByName('').HostName
6
votes

A slight tweak on @CPU-100's answer, for the local FQDN:

[System.Net.DNS]::GetHostByName($Null).HostName

6
votes

In PowerShell Core v6 (works on macOS, Linux and Windows):

[Environment]::MachineName
2
votes

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
2
votes

hostname also works just fine in Powershell

0
votes

The most descriptive way for me is:

[System.Net.DNS]::GetHostByName($env:COMPUTERNAME).HostName