PowerShell script that Changes a computer name based on the current IP address and lookup from a CSV file

1k Views Asked by At

We have a large effort underway for specific PC’s (approximately 10,000) that need to be renamed. They are in workgroup mode (not domain joined). Obviously if we can script this and do it remotely we should. I have been trying to better understand PowerShell and think it can actually be done pretty easily if I can get the code right. I need a very simple script that will:

  • Get the current IP address of the machine.
  • Compare that IP address to a CSV formatted list.
  • From the list, use the new Computer Name based on the IP Address and rename the computer.

The CSV would be very simple:

IPADDRESS,NEWCOMPNAME
192.168.0.1,NewPC1
192.168.0.2,NEWPC2
192.168.0.3,NEWPC3

This is the script I have so far but is not working:

$currentIpAddress = Test-Connection $env:COMPUTERNAME -count 1 | select Address, Ipv4Address
$csv = Import-Csv C:\test.csv
$newComputerName = $csv | where {$_.IPADDRESS -eq $currentIpAddress} | % NEWCOMPNAME
Rename-Computer -newname $newComputerName -Force -Restart 
1

There are 1 best solutions below

0
Lloyd Martin On

Thanks all for your comments and questions. I figured it out. Just to answer the questions and post the correct code for others, here goes. I am hitting Windows 8.1 x64 and Windows 10 x64. Powershell 4 and 5. If the computer name is not in the list, then the script fails (which is good) and does nothing. Also, we are running this as the local admin account, so the tests have proven successful so far.

The updated scripts are:

The CMD we are using: If Not Exist C:\Temp MD C:\Temp Copy /Y "%~dp0RenameComputerBasedOnIPList.csv" C:\temp\RenameComputerBasedOnIPList.csv powershell -ExecutionPolicy ByPass -File "%~dp0RenameComputerBasedOnIPList.ps1"

The PowerShell script that is running: Set-ExecutionPolicy -ExecutionPolicy Unrestricted $currentIpAddress = Test-Connection $env:COMPUTERNAME -count 1 | select Address, Ipv4Address $csv = Import-Csv C:\Temp\RenameComputerBasedOnIPList.csv $newComputerName = $csv | where {$_.IPADDRESS -eq $currentIpAddress.IPV4Address} | % NEWCOMPNAME Write-Host $currentIpAddress Write-Host $csv Write-Host $newComputerName Rename-Computer -NewName $newComputerName -Force -Restart

The formatted list is like this named RenameComputerBasedOnIPList.csv. IPADDRESS,NEWCOMPNAME 10.96.21.121,BADCOMPNAME 10.96.21.158,WIN10NAMECHANGE 192.168.0.2,BADCOMPNAME1 10.96.21.52,WIN81NAMECHANGE

Thanks again.