hostname — Print Machine Name#
What it is#
hostname is a built-in Windows command that prints the NetBIOS / DNS hostname of the local machine to stdout. It takes no arguments and produces a single line of output — making it ideal for scripts that need to label output or branch on machine identity without shelling out to systeminfo or WMI.
Availability#
hostname ships as C:\Windows\System32\hostname.exe on every Windows version since NT 4.0. PowerShell equivalent: $env:COMPUTERNAME or [System.Net.Dns]::GetHostName().
hostname /?
Output:
Prints the name of the current host.
HOSTNAME
Basic usage#
Running hostname with no arguments prints the machine name and exits.
hostname
Output:
myhost
Capturing the hostname in a batch variable#
Assign the output of hostname to a variable with for /f so it can be reused in the same script.
for /f "delims=" %h in ('hostname') do set MACHINE=%h
echo %MACHINE%
Output:
myhost
In a batch file use double %%h:
@echo off
for /f "delims=" %%h in ('hostname') do set MACHINE=%%h
echo Running on %MACHINE%
Output:
Running on myhost
Using %COMPUTERNAME% as an alternative#
%COMPUTERNAME% is an environment variable that holds the same NetBIOS machine name as hostname. It is always available without a subprocess call, making it marginally faster in scripts.
echo %COMPUTERNAME%
Output:
MYHOST
rem %COMPUTERNAME% is uppercase; hostname output matches the stored name
hostname
Output:
myhost
Hostname in log file names#
Embedding the hostname in a file name makes log rotation across multiple machines trivial.
systeminfo > C:\Logs\sysinfo_%COMPUTERNAME%.txt
echo Written to sysinfo_%COMPUTERNAME%.txt
Output:
Written to sysinfo_MYHOST.txt
Checking hostname on a remote machine#
hostname only reports the local machine. To get a remote machine’s hostname by IP, use nslookup or ping -a.
ping -a 192.168.1.100 -n 1
Output:
Pinging myhost [192.168.1.100] with 32 bytes of data:
Reply from 192.168.1.100: bytes=32 time<1ms TTL=128
Three layers of “machine name” on Windows#
Windows actually tracks several distinct names for the same machine, and they don’t always agree. Understanding which command returns which name is the difference between a script that works and one that mysteriously targets the wrong host.
| Source | Returns | Maximum length | Set by |
|---|---|---|---|
hostname.exe | DNS host label (lowercase as stored) | 63 chars (DNS) / 15 chars (NetBIOS) | Rename-Computer, SCCM, sysprep |
%COMPUTERNAME% | NetBIOS name (always UPPER) | 15 chars | Session env at logon |
[Dns]::GetHostName() | DNS host label (as stored) | 63 chars | Same as hostname.exe |
[Dns]::GetHostEntry('').HostName | FQDN if domain-joined | 255 chars | DNS suffix + host name |
(Get-CimInstance Win32_ComputerSystem).Name | NetBIOS name (UPPER) | 15 chars | WMI |
(Get-CimInstance Win32_ComputerSystem).DNSHostName | DNS host (lowercase) | 63 chars | WMI |
A machine renamed to BuildServer01 but still in the corp.example.com AD domain will return:
| Command | Output |
|---|---|
hostname | BuildServer01 |
echo %COMPUTERNAME% | BUILDSERVER01 |
[Dns]::GetHostEntry('').HostName | BuildServer01.corp.example.com |
[System.Net.Dns]::GetHostName()
[System.Net.Dns]::GetHostEntry('').HostName
Output:
BuildServer01
BuildServer01.corp.example.com
PowerShell equivalents and richer queries#
PowerShell exposes the same name through several APIs. Each is preferable in different contexts — $env:COMPUTERNAME for speed, Get-CimInstance for cross-machine inventory, .NET [Dns] for FQDN logic.
$env:COMPUTERNAME
Output:
MYHOST
hostname
Output:
MYHOST
(Get-CimInstance Win32_ComputerSystem).Name
Output:
MYHOST
Get-CimInstance Win32_ComputerSystem | Select-Object Name, DNSHostName, Domain, Workgroup, PartOfDomain
Output:
Name : MYHOST
DNSHostName : MYHOST
Domain : corp.example.com
Workgroup :
PartOfDomain: True
Get-ComputerInfo -Property CsName, CsDNSHostName, CsDomain, CsDomainRole
Output:
CsName : MYHOST
CsDNSHostName : MYHOST
CsDomain : corp.example.com
CsDomainRole : MemberWorkstation
FQDN, domain, and DNS suffix#
The fully-qualified domain name is the hostname plus the connection-specific DNS suffix or the primary DNS suffix. hostname never returns the FQDN — use .NET [Dns]::GetHostEntry or read the suffix directly.
[System.Net.Dns]::GetHostEntry($env:COMPUTERNAME).HostName
Output:
MYHOST.corp.example.com
ipconfig /all | findstr /C:"Primary Dns Suffix" /C:"Host Name"
Output:
Host Name . . . . . . . . . . . . : MYHOST
Primary Dns Suffix . . . . . . . : corp.example.com
Get-DnsClientGlobalSetting | Select-Object SuffixSearchList
Output:
SuffixSearchList
----------------
{corp.example.com, lab.example.com}
Renaming the machine#
Rename-Computer is the modern PowerShell way to change a Windows machine’s name; it updates both the NetBIOS name and the DNS host label. A reboot is required for the change to take full effect. The legacy netdom renamecomputer command does the same thing on Server SKUs.
Rename-Computer -NewName "BUILDSERVER02" -Force -Restart
Output:
WARNING: The changes will take effect after you restart the computer MYHOST.
For a domain-joined machine the operation requires domain admin credentials so AD can update the computer account at the same time:
Rename-Computer -NewName "BUILDSERVER02" -DomainCredential CORP\alicedev -Force -Restart
Output:
WARNING: The changes will take effect after you restart the computer MYHOST.
The legacy CMD equivalent on Server editions:
netdom renamecomputer MYHOST /NewName:BUILDSERVER02 /UserD:CORP\alicedev /PasswordD:* /Force /Reboot:0
Output:
The computer needs to be restarted in order to complete the operation.
The command completed successfully.
Reading machine name from the registry#
The persisted hostname lives in two registry keys; reading them works even when WMI is broken or the machine is offline (via offline registry mounting).
reg query "HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" /v ComputerName
reg query "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /v Hostname
reg query "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /v "NV Hostname"
Output:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName
ComputerName REG_SZ MYHOST
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
Hostname REG_SZ MYHOST
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
NV Hostname REG_SZ MYHOST
If those three values disagree, the machine is mid-rename and waiting for a reboot.
Common pitfalls#
hostnamevs%COMPUTERNAME%— both return the machine name buthostnameinvokes a subprocess; prefer%COMPUTERNAME%in tight loops.- Case difference —
hostname.exereturns the name as stored (often lower-case or mixed);%COMPUTERNAME%is always upper-case. Normalise withfor /f "usebackq" %%h in (hostname) do ...when case matters. - No remote querying —
hostnamehas no/Sflag; usenslookup <IP>,ping -a <IP>, or WMI for remote lookups. - FQDN vs short name —
hostnamereturns only the short (NetBIOS) name. For the fully-qualified domain name use PowerShell:[System.Net.Dns]::GetHostEntry('').HostName. - 15-character NetBIOS cap — NetBIOS names are limited to 15 characters; longer DNS host labels work locally but break legacy SMB/RPC name resolution. Tools that read
%COMPUTERNAME%silently truncate. - Stale
%COMPUTERNAME%after rename — the env var is set at user logon; afterRename-Computerit stays at the old name until the next sign-in even thoughhostname.exealready returns the new one. - Pending rename hides the new name — after
Rename-Computer(without-Restart)hostnamemay still report the old name until reboot; checkHKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NV Hostnamefor the queued value. - Sysprepped images — a machine cloned without sysprep keeps the source machine’s name and SID;
hostnamereports the duplicated name, AD will refuse the second join. _CLUSTER_NETWORK_NAME_overrideshostnameoutput — Microsoft Learn documents that when this environment variable is defined (Windows clustering sets it inside resource scripts),hostname.exeprints the variable’s value instead of the real machine name. Useful for cluster-aware scripts; surprising in non-cluster contexts where a straysetleaks the value.- TCP/IP must be installed —
hostname.exeis only available when the Internet Protocol (TCP/IP) component is bound to a network adapter; on stripped-down container images that omit TCP/IP it returns an error.%COMPUTERNAME%works regardless. - Any argument other than
/?is an error —hostname foodoesn’t print anything new; it just prints an error message and exits with errorlevel 1. There is no-s,-f,-d, or-ilike the Unix tool.
Real-world recipes#
Label a multi-machine inventory script#
@echo off
for /f "delims=" %%h in ('hostname') do set H=%%h
echo %H%,%DATE%,%TIME% >> C:\Audit\inventory.csv
systeminfo /FO CSV /NH >> C:\Audit\inventory.csv
echo %H% logged.
Output:
MYHOST logged.
Conditional logic based on machine name#
@echo off
for /f "delims=" %%h in ('hostname') do set H=%%h
if /i "%H%"=="buildserver" (
echo Running build tasks
) else (
echo Skipping — not the build server
)
Output:
Skipping — not the build server
Include hostname in a support-ticket dump#
echo === Machine: %COMPUTERNAME% === > support.txt
echo === Date: %DATE% %TIME% === >> support.txt
ipconfig /all >> support.txt
echo Done. Send support.txt to the helpdesk.
Output:
Done. Send support.txt to the helpdesk.
Roll a fleet-wide hostname inventory with PowerShell remoting#
Invoke-Command runs the same script block against many machines in parallel — far better than a serial for loop. Combine with Get-CimInstance for richer detail than hostname alone.
$targets = 'web01', 'web02', 'db01', 'build01'
Invoke-Command -ComputerName $targets -ScriptBlock {
[PSCustomObject]@{
NetBIOS = $env:COMPUTERNAME
DnsHost = [System.Net.Dns]::GetHostName()
FQDN = [System.Net.Dns]::GetHostEntry('').HostName
Domain = (Get-CimInstance Win32_ComputerSystem).Domain
}
} | Format-Table -AutoSize
Output:
NetBIOS DnsHost FQDN Domain
------- ------- ---- ------
WEB01 web01 web01.corp.example.com corp.example.com
WEB02 web02 web02.corp.example.com corp.example.com
DB01 db01 db01.corp.example.com corp.example.com
BUILD01 build01 build01.corp.example.com corp.example.com
Cross-reference DNS records against actual hostnames#
If hostname on 10.0.0.5 reports something different from the PTR record, DNS is stale or the machine was renamed without ipconfig /registerdns.
$ip = '10.0.0.5'
$ptr = (Resolve-DnsName $ip -ErrorAction SilentlyContinue).NameHost
$real = Invoke-Command -ComputerName $ip -ScriptBlock { hostname }
"PTR: $ptr ACTUAL: $real"
Output:
PTR: oldname.corp.example.com ACTUAL: BUILDSERVER01
Rename a machine and join it to a domain in one step#
Add-Computer accepts a -NewName parameter — useful when provisioning a freshly imaged box. The reboot completes both operations atomically.
$cred = Get-Credential CORP\domainadmin
Add-Computer -DomainName corp.example.com -NewName 'WEB-NEW01' -Credential $cred -Restart
Output:
WARNING: The changes will take effect after you restart the computer.
Branch a deployment script on machine role suffix#
A common provisioning pattern bakes role into the hostname (WEB01, DB01, BUILD01). Branch logic on the first three characters of %COMPUTERNAME%.
@echo off
set ROLE=%COMPUTERNAME:~0,3%
if /i "%ROLE%"=="WEB" (
echo Installing web role
) else if /i "%ROLE%"=="DB-" (
echo Installing database role
) else (
echo Unknown role for %COMPUTERNAME%
)
Output:
Installing web role
Related references#
| Tool | Purpose |
|---|---|
systeminfo | Full system inventory — Host Name field |
whoami | Current user and domain — companion identity command |
ipconfig /all | Host Name and Primary Dns Suffix lines |
nslookup <ip> | Reverse DNS lookup for other machines |
Rename-Computer | Modern PowerShell rename |
netdom renamecomputer | Legacy CMD rename (Server) |
Get-CimInstance Win32_ComputerSystem | WMI hostname + domain info |