How Do I Get the Localhost Name in Powershell?

How Do I Get the Localhost Name in Powershell?

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

11 Answers

You can just use the .NET Framework method:

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

also

$env:COMPUTERNAME

4

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

PS> hostname
KEITH1
2

Long form:

get-content env:computername

Short form:

gc env:computername
4

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.

2

Not specifically for Powershell version 1.0 and more of an overview of different possible ways to get information via Powershell:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.