Sign in to follow this  
Followers 0
ken82m

Rename Computer Function

7 posts in this topic

#1 ·  Posted (edited)

I've seen a few people looking for this, myself included so hear you go.

I think it's pretty self explanatory.

-Kenny

#cs ===============================================================================
 Function:      _RenameComputer( $iCompName , $iUserName = "" , $iPassword = "" )

 Description:   Renames the local computer

 Parameter(s):  $iCompName: The new computer name
 
                Required Only if PC is joined to Domain:
                    $iUserName: Username in DOMAIN\UserNamefFormat
                    $iPassword: Password of the specified account

 Returns:       1 - Succeeded (Reboot to take effect)
 
                0 - Invalid parameters
                    @error 2 - Computername contains invalid characters.
                    @error 3 - Current account does not have sufficient rights
                    @error 4 - Failed to create COM Object
                    
                Returns error code returned by WMI
                    Sets @error 1

 Author(s):  Kenneth Morrissey (ken82m)
#ce ===============================================================================

Func _RenameComputer($iCompName, $iUserName = "", $iPassword = "")
    $Check = StringSplit($iCompName, "`~!@#$%^&*()=+_[]{}\|;:.'"",<>/? ")
    If $Check[0] > 1 Then
        SetError(2)
        Return 0
    EndIf
    If Not IsAdmin() Then
        SetError(3)
        Return 0
    EndIf

    $objWMIService = ObjGet("winmgmts:\root\cimv2")
    If @error Then
        SetError(4)
        Return 0
    EndIf
    
    For $objComputer In $objWMIService.InstancesOf("Win32_ComputerSystem")
        $Return = $objComputer.rename($iCompName,$iPassword,$iUserName)
        If $oReturn <> 0 Then
            SetError(1)
            Return $oReturn
        Else
            Return 1
        EndIf
    Next
EndFunc
Edited by ken82m

My Contributions _StringMultiReplace PC Builders Console - Secure PDF Creator - Cisco VPN Installer MS DNS Server Backup Script - MS DHCP Backup Script IT Admin Console - Toggle Admin Mode - MyMovies-Add Discs Script - IT Help Desk and System Information Tool - Set On Lid Close Power Option - Streaming Media Server & Website "I believe that when we leave a place, part of it goes with us and part of us remains... Go anywhere, when it is quiet, and just listen.. After a while, you will hear the echoes of all our conversations, every thought and word we've exchanged.... Long after we are gone our voices will linger in these walls for as long as this place remains."

Share this post


Link to post
Share on other sites



I've seen a few people looking for this, myself included so hear you go.

I think it's pretty self explanatory.

-Kenny

Hi Kenny

One question.

I ran the program and checked on the computer name (MyComputer-Properties-Computer name-Full Name)

and it didn't change after I ran the program. Does the computer need to be restarted?

I did have to edit your code as there "appeared" to be a couple of errors.

$Return = $objComputer.rename($iName,$iPassword,$iUserName)

Should be

$oReturn = $objComputer.rename($iCompName,$iPassword,$iUserName)

Here is the alterened code. With my test line. No error was returned.

MsgBox(0,"Computer rename", "New name = 'test' Result code = " & _RenameComputer("test"))

Exit

#cs ===============================================================================
Function:        _RenameComputer( $iCompName , $iUserName = "" , $iPassword = "" )

Description:   Renames the local computer

Parameter(s):  $iCompName:    The new computer name

                Required Only if PC is joined to Domain:
                    $iUserName:    Username in DOMAIN\UserNamefFormat
                    $iPassword:    Password of the specified account

Returns:        1 - Succeded (Reboot to take effect)

                0 - Invalid parameters
                    @error 2 - Computername contains invalid characters.
                    @error 3 - Current account does not have sufficient rights
                    @error 4 - Failed to create COM Object
                    
                Returns error code returned by WMI
                    Sets @error 1

Author(s):     Kenneth Morrissey (ken82m)
#ce ===============================================================================

Func _RenameComputer($iCompName, $iUserName = "", $iPassword = "")
    Local $Check = StringSplit($iCompName, "`~!@#$%^&*()=+_[]{}\|;:.'"",<>/? ")
    If $Check[0] > 0 Then
        SetError(2)
        Return 0
    EndIf
    If Not IsAdmin() Then
        SetError(3)
        Return 0
    EndIf

    $objWMIService = ObjGet("winmgmts:\root\cimv2")
    If @error Then
        SetError(4)
        Return 0
    EndIf
    
    For $objComputer In $objWMIService.InstancesOf("Win32_ComputerSystem")
        $oReturn = $objComputer.rename($iCompName,$iPassword,$iUserName)
        If $oReturn <> 0 Then
            SetError(1)
            Return $oReturn
        Else
            Return 1
        EndIf
    Next
EndFunc

Share this post


Link to post
Share on other sites

Hi Kenny

One question.

I ran the program and checked on the computer name (MyComputer-Properties-Computer name-Full Name)

and it didn't change after I ran the program. Does the computer need to be restarted?

#cs ===============================================================================

Function: _RenameComputer( $iCompName , $iUserName = "" , $iPassword = "" )

Description: Renames the local computer

Parameter(s): $iCompName: The new computer name

Required Only if PC is joined to Domain:

$iUserName: Username in DOMAIN\UserNamefFormat

$iPassword: Password of the specified account

Returns: 1 - Succeded (Reboot to take effect)

0 - Invalid parameters

@error 2 - Computername contains invalid characters.

@error 3 - Current account does not have sufficient rights

@error 4 - Failed to create COM Object

Returns error code returned by WMI

Sets @error 1

Author(s): Kenneth Morrissey (ken82m)

#ce ===============================================================================


AutoIt Scripts:NetPrinter - Network Printer UtilityRobocopyGUI - GUI interface for M$ robocopy command line

Share this post


Link to post
Share on other sites

I worked out why I was confused. The name is changed (checks out now) when the script runs but the computer needs to be restarted for it to take effect (as ken82m siad in the comments).

But there was another error that I missed.

If $Check[0] > 0 Then

should be

If $Check[0] > 1 Then

New code

$name = "Test"
$temp = _RenameComputer($name)
MsgBox(0,"Computer rename", "New name = " & $name & " Result code = " & $temp & " Error = " & @error)

Exit

#cs ===============================================================================
Function:        _RenameComputer( $iCompName , $iUserName = "" , $iPassword = "" )

Description:   Renames the local computer

Parameter(s):  $iCompName:    The new computer name

                Required Only if PC is joined to Domain:
                    $iUserName:    Username in DOMAIN\UserNamefFormat
                    $iPassword:    Password of the specified account

Returns:        1 - Succeded (Reboot to take effect)

                0 - Invalid parameters
                    @error 2 - Computername contains invalid characters.
                    @error 3 - Current account does not have sufficient rights
                    @error 4 - Failed to create COM Object
                    
                Returns error code returned by WMI
                    Sets @error 1

Author(s):     Kenneth Morrissey (ken82m)
#ce ===============================================================================

Func _RenameComputer($iCompName, $iUserName = "", $iPassword = "")
    ConsoleWrite("$iCompName = '" & $iCompName & "' $iUserName = '" & $iUserName & "' $iPassword = '" & $iPassword & "'" & @CR)
    
    Local $Check = StringSplit($iCompName, "`~!@#$%^&*()=+_[]{}\|;:.'"",<>/? ")
    ConsoleWrite("$Check[0] = " & $Check[0] & "$Check[1] = " & $Check[1] & @CR)
    
    If $Check[0] > 1 Then
        SetError(2)
        Return 0
    EndIf
    If Not IsAdmin() Then
        SetError(3)
        Return 0
    EndIf

    $objWMIService = ObjGet("winmgmts:\root\cimv2")
    If @error Then
        SetError(4)
        Return 0
    EndIf
    
    For $objComputer In $objWMIService.InstancesOf("Win32_ComputerSystem")
        $oReturn = $objComputer.rename($iCompName,$iPassword,$iUserName)
        If $oReturn <> 0 Then
            SetError(1)
            Return $oReturn
        Else
            Return 1
        EndIf
    Next
EndFunc

Works perfectly now. :)

Thanks to ken82m this will come in handy

John Morrison

Share this post


Link to post
Share on other sites

Works perfectly now.

Thanks to ken82m this will come in handy

John Morrison

Corrected original post. Enjoy guys :)


My Contributions _StringMultiReplace PC Builders Console - Secure PDF Creator - Cisco VPN Installer MS DNS Server Backup Script - MS DHCP Backup Script IT Admin Console - Toggle Admin Mode - MyMovies-Add Discs Script - IT Help Desk and System Information Tool - Set On Lid Close Power Option - Streaming Media Server & Website "I believe that when we leave a place, part of it goes with us and part of us remains... Go anywhere, when it is quiet, and just listen.. After a while, you will hear the echoes of all our conversations, every thought and word we've exchanged.... Long after we are gone our voices will linger in these walls for as long as this place remains."

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

I've seen a few people looking for this, myself included so hear you go.

I think it's pretty self explanatory.

-Kenny

Hiya Kenny, I was hoping you might be able to help me here. I love the simplicity of your code, very easy to understand and manipulate. But I was wodering if there is a way to have a popup prompt asking for a new computer name? Here's my situation;

I have automated our entire imaging, and scripted install process for computers at my company for Windows 7. When they are done they are sitting at the desktop of the local administrator account, already joined to the domain with a generic computer name.

What I would like is to have a script I can edit and then compile to an EXE usiing AutoIt, that will pop up a window that states "Please enter a new computername." and a place to enter it. Then upon succesful entry, prompt for reboot. Is this Possible?

I found this code over at experts-exchange, but it has Windows activation included in it as well, which I don't need because mine auto activate. Also this doesn't prompt to reboot. *edit - Apparently it does prompt for reboot*

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_icon=mozillacrystal.ico
#AutoIt3Wrapper_outfile=RenameComputer.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Res_Description=Change Computer Names. Used for Windows 7 Imaging
#AutoIt3Wrapper_Res_Fileversion=0.0.0.0
#AutoIt3Wrapper_Res_LegalCopyright=SaLus
;Please keep copyright info here. Thank you :)
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <ComboConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>

Opt("GUIOnEventMode", 1)
Const $JOIN_DOMAIN = 1
Const $ACCT_CREATE = 2
Const $ACCT_DELETE             = 4
Const $WIN9X_UPGRADE           = 16
Const $DOMAIN_JOIN_IF_JOINED   = 32
Const $JOIN_UNSECURE           = 64
Const $MACHINE_PASSWORD_PASSED = 128
Const $DEFERRED_SPN_SET        = 256
Const $INSTALL_INVOCATION      = 262144

Dim $oMyError
Dim $UserName
Dim $Password
Dim $objComputer
Dim $objNetwork
Dim $ComputerName
Dim $objWMIService
Dim $res
Dim $result
Dim $ret


$Form1 = GUICreate("Image Finisher", 456, 217, 192, 124)
$Group1 = GUICtrlCreateGroup(" Computer Name ", 10, 10, 246, 51)
$ComputerName = GUICtrlCreateInput("[MyComputerName]", 20, 30, 226, 21)
GUICtrlCreateGroup("", -99, -99, 1, 1)

$Button1 = GUICtrlCreateButton("Set Configuration", 145, 175, 160, 25, $WS_GROUP)
GUICtrlSetOnEvent($Button1,"_SetCompName")

$Group3 = GUICtrlCreateGroup(" Activation Type ", 10, 75, 246, 50)
$KMSAct = GUICtrlCreateRadio("KMS", 20, 90, 100, 25)
GUICtrlSetOnEvent($KMSAct, "_UseKMS")

$MAKAct = GUICtrlCreateRadio("MAK", 120, 90, 100, 25)
GUICtrlSetOnEvent($MAKAct, "_UseMAK")

$MAKKey = GUICtrlCreateEdit("", 270, 17, 170, 110, BitOR($ES_AUTOVSCROLL,$ES_WANTRETURN))
GUICtrlSetData(-1, "If the computer is going to be off the network for > 180 days, choose MAK and input key here.")
GUICtrlSetState(-1, $GUI_DISABLE)
GUICtrlCreateGroup("", -99, -99, 1, 1)

GUISetOnEvent($GUI_EVENT_CLOSE,"_Exit")
GUISetState(@SW_SHOW)

While 1
    Sleep(10)
WEnd

$oMyError = ObjEvent("AutoIt.Error","MyErrFunc")

Func _UseMAK()
    GUICtrlSetState($MAKKey, $GUI_ENABLE)
EndFunc

Func _UseKMS()
    GUICtrlSetState($MAKKey, $GUI_DISABLE)
EndFunc

Func _SetCompName()
    GUICtrlSetData($Button1,"Adding Computer")
    GUICtrlSetState($Button1,$GUI_DISABLE)
    GUICtrlSetState($ComputerName,$GUI_DISABLE)

    If GUICtrlRead($ComputerName) == "[MyComputerName]" Or GUICtrlRead($ComputerName) == "" Then
        MsgBox(16,"ERROR","Please name the computer!")
        GUICtrlSetData($Button1,"Set Computer Name")
        GUICtrlSetState($Button1,$GUI_ENABLE)
        GUICtrlSetState($ComputerName,$GUI_ENABLE)
    Else
        If NOT BitAND(GUICtrlRead($KMSAct),$GUI_CHECKED) OR NOT BitAND(GUICtrlRead($MAKAct),$GUI_CHECKED) Then
            MsgBox(16,"ERROR","Please choose an Activation Method")
            GUICtrlSetData($Button1,"Set Computer Name")
            GUICtrlSetState($Button1,$GUI_ENABLE)
            GUICtrlSetState($ComputerName,$GUI_ENABLE)
        Else
            $objNetwork = ObjCreate("WScript.Network")
            $strComputer = $objNetwork.ComputerName

            $objWMIService = ObjGet("Winmgmts:root\cimv2")
            For $objComputer In $objWMIService.InstancesOf("Win32_ComputerSystem")
                ; Add your credentials here
                $res = $objComputer.rename(GUICtrlRead($ComputerName),"{PASSWORD}","{DOMAIN\USERNAME}")
                If $res <> 0 Then
                    If $res = 2224 Then
                        MsgBox(16,"Error","Error Code: " & $res & @CR & "Account already exists. Please delete from Active Directory.")
                        GUICtrlSetState($Button1,$GUI_ENABLE)
                        GUICtrlSetState($ComputerName,$GUI_ENABLE)
                        GUICtrlSetData($Button1,"Set Computer Name")
                    ElseIf $res == 5 Then
                        MsgBox(16,"Error","Error Code: " & $res & @CR & "Access Denied.")
                        GUICtrlSetState($Button1,$GUI_ENABLE)
                        GUICtrlSetState($ComputerName,$GUI_ENABLE)
                        GUICtrlSetData($Button1,"Set Computer Name")
                    Else
                        MsgBox(16,"Error","Error renaming or adding the computer to the domain" & @CR & "Error Code: " & $res)
                        GUICtrlSetState($Button1,$GUI_ENABLE)
                        GUICtrlSetState($ComputerName,$GUI_ENABLE)
                        GUICtrlSetData($Button1,"Set Computer Name")
                    EndIf
                Else
                    GUICtrlSetState($Button1,$GUI_DISABLE)
                    GUICtrlSetState($ComputerName,$GUI_DISABLE)
                    MsgBox(64,"Success","Computer has been renamed to: " & GUICtrlRead($ComputerName))
                    RunOnce()
                EndIf
            Next
        EndIf
    EndIf
EndFunc

Func RunOnce()
    $file = FileOpen("C:\Users\Public\Documents\delete.bat", 2)
    FileWrite( $file, "Del C:\Users\Public\Documents\RenameComputer.exe" & @CRLF)
    FileWrite( $file, "Attrib -r" & @CRLF)
    FileWrite( $file, "DEL %0")
    FileClose($file)
    RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", "applysettings", "REG_SZ", "C:\Users\Public\Documents\delete.bat")

    If BitAND(GUICtrlRead($KMSAct), $GUI_CHECKED) Then
        $DoActivate = MsgBox(36,"Activation","Activate Windows 7 with KMS?" & _
            @CRLF & "NOTE: If this machine is going to be off campus for more than 180 days DO NOT ACTIVATE. Please use a MAK Key instead")
        If $DoActivate = 6 Then
            MsgBox(64,"Processing...","Activation will continue after you hit OK. Please wait for the confirmation box to appear before restarting." & _
                    @CR & "Activation takes between 10-30 seconds.")
            Run(@ComSpec & " /c slmgr /ato")
            GUICtrlSetData($Button1,"REBOOT COMPUTER")
            GUICtrlSetState($Button1,$GUI_ENABLE)
            GUICtrlSetOnEvent($Button1,"_Reboot")
        Else
            $OKReboot = MsgBox(1,"Reboot Needed","This machine must reboot to complete configuration")
            If $OKReboot = 1 Then
                _Reboot()
            Else
                Exit
            EndIf
        EndIf
    Else
        $GetMAKKey = GUICtrlRead($MAKKey)
        Run(@ComSpec & " /c slmgr /ipk " & $GetMAKKey)
        GUICtrlSetData($Button1,"REBOOT COMPUTER")
        GUICtrlSetState($Button1,$GUI_ENABLE)
        GUICtrlSetOnEvent($Button1,"_Reboot")
    EndIf
EndFunc

Func _Reboot()
    Run(@ComSpec & " /c " & 'shutdown -r -f -t 05', "", @SW_HIDE)
EndFunc

Func MyErrFunc()
    $HexNumber = hex($oMyError.number,8)
    Msgbox(0,"","We intercepted a COM Error !" & @CRLF & _
            "Number is: " & $HexNumber & @CRLF & _
            "Windescription is: " & $oMyError.windescription )
EndFunc

Func _Exit()
    Exit
EndFunc

Thanks in advance for any info you might be able to provide! :-)

Edited by Daedelous

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0