powershellrenamepowershell-5.0computer-name

How to rename a domain computer in Powershell


I've been trying to rename a domain computer with the following script:

$username = "domain\username"
$password = "password"
$ip = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
$hostname = (nslookup $ip)[3]
$hostname = $hostname.replace(" ", "")
$hostname = $hostname.split(":")[1]
$hostname = $hostname.split(".")[0].ToLower()
Rename-Computer -NewName $hostname -DomainCredential $username  -Restart -Force

It does everything I desire apart from inputting the password which at this point is a manual process. Can someone advise me on how to get it to input from $password into the prompt box so that I can completely automate the process?

Alternatively, if there's a better way to do it in Powershell, I'm open to going another direction.


Solution

  • You can use this code:

    $Username = "DomainUserName"
    $Password = "PlainPassword" | ConvertTo-SecureString -AsPlainText -Force
    $Creds = New-Object System.Management.Automation.PSCredential($Username ,$Password)
    
    
    Rename-Computer -NewName $newComputerName -ComputerName $OldName -Restart -DomainCredential $Creds