0

Have been trying to write a script to rename computer with a set prefix and suffix with prompt for the user to enter a 3-6 digit number in between but seem to be struggling. I have tried various methods and I think this is the correct one but it does not seem to change. If I run each line manually it works but not if I run the script? Has to be something simple I am missing but I am struggling to notice what it is. I have commented all the extra code out currently to just run the 3 lines but no change. Any help would be greatly appreciated.

Write-Host
Write-Host "PC renaming" 
Write-Host
Write-Host -ForegroundColor Red "NOTE: Your computer will automatically 
reboot once complete"
Write-Host
$shutdowntime = 10
$pcname = Read-Host -Prompt 'Input the new PC name'
$newname = 'KBOXFD5'+ $pcname + 'PC'
Rename-Computer -NewName $newname
Write-Host
Write-Host "The device will rebooted in $shutdowntime seconds..." 
dlands
  • 1
  • 2
  • 1
    How do you run the script? [Edit] the question and show actual code. Don't split the script in several parts in the question, as of now it's hard to see which stuff is there and which isn't. – vonPryz Nov 08 '21 at 08:16
  • Hi vonPryz, I right click and use run from Powershell command – dlands Nov 08 '21 at 08:37
  • @dlands: Open Powershell_ISE and execute from there. You would be able to see the details and errors... Once everything is fine, you can save it as .ps1 and execute from Powershell command prompt. – Ranadip Dutta Nov 08 '21 at 09:22
  • 2
    @dlands You will need to run the PowerShell in an administrative context to sucessfully execute `rename-computer`. Another thing to consider is the `execution policy` of the system/user. – CraftyB Nov 08 '21 at 11:38
  • 1
    Also, **never** blindly accept whatever a user types in. You need to check if the new computername you construct using that input doesn't exceed the 15 character limit and does not contain any invalid characters as well. See [this](https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/naming-conventions-for-computer-domain-site-ou) – Theo Nov 08 '21 at 12:59
  • Thanks all, I think it must be the admin side of it. Need to run .ps1 as admin so looking for a way to do that now. I have a batch file that does the same thing but was trying for a powershell one but seems to be easier to use the batch at the moment? – dlands Nov 08 '21 at 15:01
  • You can try different approach's: - `Invoke-Command { powershell.exe -File ... } -RunAsAdministrator` - `Start-process powershell.exe -Verb RunAs -ArgumentList ''` - You can include a `#Requires -RunAsAdministrator` statement at top of the script. – Hazrelle Nov 09 '21 at 14:46
  • Thanks Hazrelle, I will look into that more I think. – dlands Nov 10 '21 at 19:18
  • Found exactly what I needed here. Works just as needed. https://stackoverflow.com/questions/7690994/running-a-command-as-administrator-using-powershell – dlands Nov 12 '21 at 16:52

0 Answers0