How to Rename Windows Machines with PowerShell

Key Takeaways

  • PowerShell Script Flexibility: The script showcases the power and flexibility of PowerShell in managing computer settings, emphasizing the importance of PowerShell in modern IT administration.
  • Ease of Renaming Computers: Highlights the ease with which IT professionals can rename both domain-joined and non-domain computers.
  • Domain Admin Credentials: Stresses the necessity of domain admin credentials for renaming domain-joined machines unless executed by a Domain Admin.
  • Automated Reboot Option: The script includes an optional automated reboot feature, which is crucial for the changes to take effect.
  • Security Considerations: Underlines the importance of handling credentials securely in scripts, as demonstrated by the conversion of plain text passwords to secure strings.
  • Error Handling and Validation: The script incorporates robust error handling and validation, ensuring safe and reliable execution.
  • Real-World Application: Illustrates practical use cases, particularly for IT professionals and Managed Service Providers (MSPs) in streamlining computer management tasks.

Managing IT infrastructure efficiently is pivotal for the smooth operation of modern businesses. Among numerous tasks, renaming computers, particularly in a domain environment, can be crucial for maintaining system organization, adhering to naming conventions, and ensuring security protocols. PowerShell scripts have emerged as powerful tools for automating such tasks, offering precision, speed, and scalability.

Background

The PowerShell script we’re exploring is designed to automate the process of renaming computers. This capability is particularly valuable for IT professionals and Managed Service Providers (MSPs) who manage large networks with numerous machines. It addresses the need for a consistent and error-free approach to renaming, which is crucial in environments where computer names are often aligned with specific roles, departments, or usage policies.

The Script:

#Requires -Version 5.1

<#
.SYNOPSIS
    Renames either domain-joined or non-domain-joined machines. Requires a Domain Admin's username and password for domain-joined computers, unless run as a Domain Admin.
.DESCRIPTION
    Renames either domain-joined or non-domain-joined machines. Requires a Domain Admin's username and password for domain-joined computers, unless run as a Domain Admin.
.EXAMPLE
    -NewName "ReplaceWithNewName"

    WARNING: The changes will take effect after you restart the computer KYLE-WIN10-TEST.

    HasSucceeded OldComputerName           NewComputerName          
    ------------ ---------------           ---------------          
    True         KYLE-WIN10-TEST           ReplaceWithNewName               



    WARNING: This script takes effect after a reboot. Use -Reboot to have this script reboot for you.

PARAMETER: -DomainUser "UsernameForDomainAdmin" -DomainPassword "SuperSecretPassword1"
    Domain Joined machines require a domain admins creds when not ran as a Domain Admin (System is not a Domain Admin).

PARAMETER: -Reboot
    Reboots the computer 5 minutes after the script is ran.
.EXAMPLE
    -NewName "ReplaceWithNewName" -Reboot

    This is a domain joined machine. Testing for secure domain connection...
    WARNING: The changes will take effect after you restart the computer KYLE-WIN10-TEST.

    HasSucceeded OldComputerName           NewComputerName          
    ------------ ---------------           ---------------          
    True         KYLE-WIN10-TEST           ReplaceWithNewName               

    WARNING: Reboot specified scheduling reboot for 06/13/2023 12:09:53...

.OUTPUTS
    None
.NOTES
    OS: Win 10+, Server 2016+
    Release: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$NewName,
    [Parameter()]
    [String]$DomainUser,
    [Parameter()]
    [String]$DomainPassword,
    [Parameter()]
    [Switch]$Reboot = [System.Convert]::ToBoolean($env:reboot)
)

begin {
    # If script forms are used overwrite the params with those values.
    if ($env:newComputerName -and $env:newComputerName -notlike "null") { $NewName = $env:newComputerName }
    if ($env:domainAdminUsername -and $env:domainAdminUsername -notlike "null") { $DomainUser = $env:domainAdminUsername }
    if ($env:domainAdminPassword -and $env:domainAdminPassword -notlike "null") { 
        $DomainPassword = $env:domainAdminPassword
        # We should overwrite the environmental variable with a secure string 
        $env:domainAdminPassword = $env:domainAdminPassword | ConvertTo-SecureString -AsPlainText -Force 
    }

    # Converts the username and password into a powershell credential object
    if ($DomainUser -and $DomainPassword) {
        $Credential = New-Object System.Management.Automation.PsCredential("$DomainUser", $($DomainPassword | ConvertTo-SecureString -AsPlainText -Force))
    }

    # If a domain password was given we should overwrite it with a secure string
    if ($DomainPassword) {
        $DomainPassword = $DomainPassword | ConvertTo-SecureString -AsPlainText -Force
    }

    # Checks if script is running as an elevated user
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    # Check if machine is domain joined
    function Test-IsDomainJoined {
        return $(Get-CimInstance -Class Win32_ComputerSystem).PartOfDomain
    }

    # Check if script is running as System
    function Test-IsSystem {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        return $id.Name -like "NT AUTHORITY*" -or $id.IsSystem
    }

    # Check if script is running as a domain admin
    function Test-IsDomainAdmin {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        return $p.IsInRole("Domain Admins")
    }

    # Double check that this script has something to do.
    if ($NewName -eq $env:computername) {
        Write-Error "[Error] New name is the same as the current hostname."
        exit 1
    }

    # Error out if not provided with a new name
    if (-not $Newname) {
        Write-Error "[Error] Please specify a name with the NewName parameter!"
        exit 1
    }
}
process {
    # If not running as the system user script needs to be running as an elevated user.
    if (-not (Test-IsElevated) -and -not (Test-IsSystem)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # Warn end-users if theyre giving the computer too long of a name.
    if ($NewName.Length -gt 15) {
        Write-Warning -Message "The New Computer Name $NewName exceeds 15 characters! In some instances you may only see the first 15 characters."
    }

    # Preparing Splat
    $ArgumentList = @{
        "ComputerName" = $env:computername
        "Force"        = $True
        "NewName"      = $NewName
        "PassThru"     = $True
    }

    # If it's domain joined we'll have to check a couple things to make sure this is possible
    if (Test-IsDomainJoined) {
        Write-Host -Object "This is a domain joined machine. Testing for secure domain connection..."

        # The domain controller will need to be reachable for the rename to apply
        if (-not (Test-ComputerSecureChannel -ErrorAction Ignore)) {
            Write-Error -Message "[Error] A secure connection to the domain controller cannot be established!
            Please ensure the domain is reachable and there are no machines with identical names!"
            exit 1
        }

        # Domain joined machines require a domain admin to change the name
        if (-not $Credential -and -not (Test-IsDomainAdmin)) {
            Write-Error -Message "[Error] The -DomainUser and -DomainPassword parameter is missing. 
            The username and password for a domain admin is required when not ran as a Domain Admin for domain joined machines!"
            exit 1
        }

        # Adding credentials to the splat
        if ($Credential) {
            $ArgumentList["DomainCredential"] = $Credential
        }
    }

    # Saving the results to check later
    $Result = Rename-Computer @ArgumentList

    # Letting the end-user know the result
    $Result | Format-Table | Out-String | Write-Host

    # Error out on failure
    if (-not $Result.HasSucceeded) {
        Write-Error -Message "[Error] Failed to rename computer!"
        exit 1
    }

    # If a reboot was specified schedule it for 5 minutes from now.
    if ($Reboot) {
        Write-Warning -Message "Reboot specified scheduling reboot for $((Get-Date).AddMinutes(5))..."
        Start-Process -FilePath "cmd.exe" -ArgumentList "/C shutdown.exe /r /t 300"
    }
    else {
        Write-Warning -Message "This script takes effect after a reboot. Use -Reboot to have this script reboot for you."
    }
    exit 0
}
end {
    
    
    
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

This script operates by automating the renaming process of Windows computers, either domain-joined or non-domain-joined. Here’s a step-by-step explanation:

  • Parameter Declaration: The script starts by declaring parameters like NewName, DomainUser, DomainPassword, and Reboot. These inputs dictate the new computer name, domain credentials, and whether to reboot the machine after renaming.
  • Initial Checks and Credential Handling: It checks for environment variables and converts plaintext passwords into secure strings. For domain operations, it transforms user credentials into a PowerShell credential object.
  • Functions: Several functions are defined to check if the script is running with elevated privileges, if the computer is part of a domain, if it’s running as a system user, and if the user is a domain admin.
  • Validation: The script validates that a new name is provided and that it’s different from the current name. It also checks for administrative privileges and domain connectivity if applicable.
  • Execution: If all checks pass, the Rename-Computer cmdlet is called with appropriate parameters. This cmdlet is the core command that executes the renaming process.
  • Reboot Handling: If the -Reboot switch is used, the script schedules a system reboot in 5 minutes to apply the changes.

Potential Use Cases

Imagine an MSP managing a network for a large organization that’s restructuring its departments. The MSP uses this script to efficiently rename computers across the network to reflect the new departmental structure, ensuring consistency and reducing manual effort.

Comparisons

Traditional methods of renaming computers often involve manual intervention, either through system properties or domain controller tools. This script offers a more streamlined and error-resistant approach, particularly useful when handling multiple machines.

FAQs

Q1: Can this script rename computers in bulk?
A: Yes, though you might need to modify it to loop through a list of computers and their new names.

Q2: Is it secure to use plaintext passwords in the script?
A: The script converts plaintext passwords to secure strings, enhancing security. However, it’s recommended to handle credentials cautiously.

Q3: Do I need administrative privileges to run this script?
A: Yes, administrative privileges are required, especially for renaming domain-joined computers.

Implications

While this script streamlines a routine task, improper use could lead to naming conflicts, network issues, or security vulnerabilities. It’s vital to plan and review renaming strategies to ensure they align with organizational policies and IT infrastructure norms.

Recommendations

  • Test Thoroughly: Run the script in a test environment before deploying in production.
  • Secure Credentials: Handle and store credentials securely, preferably using encrypted methods.
  • Document Changes: Keep a record of changes for troubleshooting and auditing purposes.

Final Thoughts

In the realm of IT management, tools like NinjaOne offer comprehensive solutions for managing and automating IT tasks. Integrating such scripts into a broader management framework like NinjaOne can enhance efficiency, reduce errors, and provide greater control over IT environments. By leveraging the power of automation and central management, IT professionals can focus on strategic initiatives rather than routine tasks.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).