Why are you doing this...
$ipaddarray = $value.split('.')
$ipaddress = $ipaddarray[0]+'.'+$ipaddarray[1]+'.'+$ipaddarray[2]+'.'+$ipaddarray[3]
.. vs just using the built-in NIC/network cmdlets to get the IPA as a simple string.
(Get-NetIPAddress).IPv4Address
Getting a system hostname is a default system variable on every Windows host. Just use:
$env:COMPUTERNAME
Or
hostname
You should be able to do just what is described in the articles below.
Rename-Computer -NewName 'SomeHostname' -Restart
Dynamically rename an AWS Windows host deployed via a syspreped AMI
Deploy a Windows Server 2016 AMI
Connect to the Windows instance and customize it as required
Create a startup PowerShell script to set the hostname that will be invoked on boot before the unattended installation begins
Run InitializeInstance.ps1 -Schedule to register a scheduled task that initializes the instance on the next boot
Modify SysprepInstance.ps1 to replace the cmdline registry key after sysprep is complete and prior to shutdown
Run SysprepInstance.ps1 to sysprep the machine.
#Set my hostname based on my internal IP address
$instanceName = (((Invoke-WebRequest -UseBasicParsing -Uri http://169.254.169.254/latest/meta-data/hostname).Content).split(".")[0]).replace("ip-172-31","TCG")
#Change the hostname in the unattend.xml file
$filePath = "C:\Windows\Panther\Unattend.xml"
$AnswerFile = [xml](Get-Content -Path $filePath)
$ns = New-Object System.Xml.XmlNamespaceManager($answerFile.NameTable)
$ns.AddNamespace("ns", $AnswerFile.DocumentElement.NamespaceURI)
$ComputerName = $AnswerFile.SelectSingleNode('/ns:unattend/ns:settings[@pass="specialize"]/ns:component[@name="Microsoft-Windows-Shell-Setup"]/ns:ComputerName', $ns)
$ComputerName.InnerText = $InstanceName
$AnswerFile.Save($filePath)
#Start the OOBE
Start-Process C:\windows\system32\oobe\windeploy.exe -Wait
How to rename an AWS EC2 instance during provisioning using PowerShell
Rename-Computer -NewName 'SomeHostname' -Restart
How to change & verify hostname in windows server 2012 (AWS EC2)
Method 1. Open cmd and type:
SCONFIG and you will get selection menu where #2 says Computer Name:
Method 2. From cmd type:
netdom renamecomputer %computername% /newname:<NewName> /reboot:0
Method 3. From the PowerShell console:
netdom renamecomputer $env:computername /newname:<NewName> /reboot:0
To verify the name form cmd type:
nbtstat -A xxx.xxx.xxx.xxx (where x is the ip address)
Another way to verify the name form cmd just type "hostname" without any parameters:
hostname