Search code examples
powershellwmic

Rename PC with WMIC


I need to achieve something very simple. As part of a PowerShell script which will be run on several hundred new Windows 7 machines I need to rename them prior to joining them to domain.

I have done some searching, and one common solution seems to be:

wmic computersystem where name="%COMPUTERNAME%" call rename name="NEW-NAME"

However, from testing, I get the following error upon execution:

Invalid Verb Switch

Is this incorrect? Is there a better alternative (without upgrading PowerShell on the machines)

EDIT: If run through batch, the file returns success, but doesn't actually rename the machine (even after a reboot)


Solution

  • Why not just rename this way (it's a snippet I use quite a lot):

    Function Rename-Computer([string]$newComputerName)
    {
        $computer = Get-WmiObject -Class Win32_ComputerSystem
        $computer.rename($newComputerName)
    }
    

    Credit: http://powershell.com/cs/media/p/922.aspx

    Further research suggests that it could be the double quotes, another way you could run this is:

    cmd /c "wmic computersystem where name='%computername%' call rename name='NEW-NAME'"
    

    Note how the double quotes have been replaced with single quotes and the whole command passed to cmd.exe is passed inside a double quoted string.

    If you have other WMIC commands you need to issue then this is probably less painful than coming up with alternative PowerShell solutions.