I'm experiencing differences between the value of $env:ComputerName
and the output of the hostname.exe command in a script that checks a machine's hostname against a predefined set:
if ($env:ComputerName -in $hostnames) { ... }
However, it seems like I cannot rely on the value of $env:ComputerName
because it sometimes differs from the hostname of a machine on the network:
PS> hostname
Example
PS> $env:ComputerName
EXAMPLE
Besides the casing, why would these provide different values? On one machine, the name is significantly different between the two—hostname.exe outputs the expected name while $env:ComputerName
contains an incorrect name. Does PowerShell retrieve the value from a different source than hostname.exe?
The $env
namespace is populated by PowerShell.exe
when it loads from the set of environment variables. It pulls these from the process that started it or from the registry. $env:COMPUTERNAME
should match the %COMPUTERNAME%
environment variable. Notably, when the value of an environment variable changes, it does not update that value in all open processes.
I'm not 100% sure what hostname.exe
pulls from, but I believe that it requires that TCP/IP be loaded on a system. It may be querying the network name that the host network adapter is listening for, or may be querying the network configuration (via the registry or some other method).
The most common instance where the two values don't match is after a computer has been renamed but before it has been restarted to complete the name change.