Host rename powershell
Automatically Setting Computer Name from Local IP Address
In certain scenarios, it may be necessary to automatically set the computer name based on its local IP address. This can be particularly useful in environments where dynamic assignment of computer names is desired. Below is a PowerShell script that accomplishes this task.
# Get the local IP address
$localIpAddress = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias 'Ethernet') | Select-Object -ExpandProperty IPAddress
# Retrieve the hostname using the local IP address
$fqdn = (nslookup $localIpAddress | Select-String -Pattern 'Name:' | Select-Object -First 1).Line.Split(':')[1].Trim()
# Extract the hostname from the FQDN
$newComputerName = $fqdn.Split('.')[0]
# Fallback computer name if DNS resolution fails
$fallbackComputerName = "failure"
# If DNS resolution fails (i.e., $fqdn is empty), use the fallback computer name
if ([string]::IsNullOrEmpty($fqdn)) {
$newComputerName = $fallbackComputerName
}
# Output the new computer name
Write-Host "New Computer Name: $newComputerName"
# Get a WMI object representing the current computer
$currentComputer = Get-WmiObject Win32_ComputerSystem
# Attempt to change computer name to $newComputerName
Write-Host "Attempting to change computer name to $newComputerName"
$currentComputer.Rename($newComputerName)
How It Works
-
Get Local IP Address: The script retrieves the local IP address of the computer.
-
Retrieve Hostname: Using the local IP address, the script performs a DNS lookup to obtain the fully qualified domain name (FQDN) of the computer.
-
Extract Computer Name: The script extracts the hostname from the FQDN.
-
Fallback Name: If DNS resolution fails, indicating that the FQDN is empty, a fallback computer name is used.
-
Set Computer Name: The script attempts to set the computer name to the extracted or fallback name using WMI (Windows Management Instrumentation).
-
Output: The new computer name is displayed in the console along with the attempt to change the computer name.
This script provides a flexible solution for automatically setting the computer name based on its local IP address, ensuring dynamic and efficient management of computer naming in network environments.
Credits: Johannes Nguyen, Jakob Marx