Rename-Computer; Restart-Computer -wait

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Kevin Greer Kevin Greer 1 week ago.

  • Author
    Posts
  • #73000
    Profile photo of Kevin Greer
    Kevin Greer
    Participant
    #Change Computer Name
    #------------------------------------------------------------------------------------------
    Write-Verbose -Message "Changing computer name.  Old name: $ComputerName, New name: $NewComputername" -Verbose
    rename-computer -computername $ComputerName -newname $NewComputername -domaincredential $Credential -Force
    
    #Restart Computer
    #------------------------------------------------------------------------------------------
    Write-Verbose -Message "Rebooting $ComputerName.  Please wait" -Verbose
    Restart-Computer -ComputerName $ComputerName -Force -Wait -Timeout 300
    #Test if changing the computername causes the -wait to fail
    

    When the computer is renamed, it has to be rebooted, but once it boots back up it is now using the new name. Is the -wait parameter waiting for the old computer name, then times out? If it is, what is a good way to rename, reboot, wait for the computer to be accessible (WinRM), then continue with the script succesfully?

  • #73001
    Profile photo of Don Jones
    Don Jones
    Keymaster

    It would wait for the old name.

    Do {
      $keep_going = $false
      Start-Sleep 1000
      Try {
       $session = new-pssession -computer $newcomputername -ea stop
      } Catch {
        $keep_going = $true
      }
    } While ($keep_going)
    

    Something along those lines. When you exit the loop, you'll have a remoting session in $session.

  • #73063
    Profile photo of Kevin Greer
    Kevin Greer
    Participant

    Thank you Don, I modified this some to include a 5 minute timeout then check if $session exists after the loop is exited.

    Write-Verbose -Message "Rebooting $ComputerName.  Please wait" -Verbose
    Restart-Computer -ComputerName $ComputerName -Force
    $count = 0
    Do {
      $keep_going = $false
      $count +=1
      Start-Sleep -Seconds 1
      if($count -eq 0 -or ($count % 5) -eq 0){ 
        Write-Verbose -Message "Attempting Connection to $NewComputername" -Verbose
      }
      Try {
       $session = new-pssession -ComputerName $NewComputername -ErrorAction Stop
      } Catch {
        $keep_going = $true
      }
    } While ($keep_going -or $count -ge 300)
    
    if($session){
      Write-Verbose -Message "Connecton Established to $NewComputername"
      Remove-PSSession -Session $session
    }
    else{
      Write-Warning -Message "Connecton to $NewComputername failed"
    }
    

You must be logged in to reply to this topic.