This is straightforward via the Win32_ComputerSystem
WMI class:
# Fetch the `Win32_ComputerSystem` instance on localhost
$CS = Get-CimInstance Win32_ComputerSystem
# Unjoin old domain
$CS |Invoke-CimMethod -MethodName UnjoinDomainOrWorkGroup -Arguments @{
FUnjoinOptions = 4
Password = $DomainPassword
UserName = $DomainUser
}
# Rename the computer
$CS |Invoke-CimMethod -MethodName Rename -Arguments @{
Name = $NewComputerName
}
# Join the new domain
$CS |Invoke-CimMethod -MethodName JoinDomainOrWorkGroup -Arguments @{
AccountOU = 'OU=Computers,DC=new,DC=domain,DC=tld'
FJoinOptions = 0
Name = 'new.domain.tld'
Password = $NewDomainPassword
UserName = $NewDomainUser
}