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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge2View Question on Stackoverflow
Solution 1 - .NetStrelokView Answer on Stackoverflow
Solution 2 - .NetKeith HillView Answer on Stackoverflow
Solution 3 - .NetRaYellView Answer on Stackoverflow
Solution 4 - .NetgrepitView Answer on Stackoverflow
Solution 5 - .NetGary PendleburyView Answer on Stackoverflow
Solution 6 - .NetfelixfbeckerView Answer on Stackoverflow
Solution 7 - .NetBillMuxView Answer on Stackoverflow
Solution 8 - .NetGarricView Answer on Stackoverflow
Solution 9 - .NetGucu112View Answer on Stackoverflow
Solution 10 - .NetKentMarionVGView Answer on Stackoverflow