Get List of PC and Change Name PowerShell script

Netanel Elhadad
Netanel Elhadad used Ask the Experts™
on
hello, i want Powershell script that give me list of all the computers in AD with the option of select one of them by number and after it i can change the computer name that i selected.

exsmple:
Get-ADComputer -Filter * -Property * | Select-Object CN
1. WS1
2. WS2
3. WS3
4. WS4
Select a PC: 2

Write-Host "Please enter your new computer name: "
$newname = Read-Host
## netdom renamecomputer $oldname /newname:$newname /userd:* /passwordd:* /usero:* /passwordo:* /reboot:10 /force
Rename-Computer -ComputerName "$oldname" -NewName "$newname" -DomainCredential amal-p\admin -Force -PassThru -Restart
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
I would use Out-GridView for the PC selection.
$pc = Get-ADComputer -Filter * | Select-Object CN | 
                      Out-GridView -OutputMode Single -Title 'Select one PC to rename'
$newname = Read-Host 'Please enter your new computer name: '
Rename-Computer -ComputerName $pc.CN -NewName $newname -DomainCredential amal-p\admin -Force -PassThru -Restart

Open in new window

Please do not enclose string variables in double quotes, unless you are concatening. As I showed, just use them without.
Netanel ElhadadIT System Administrator

Author

Commented:
i add the " -Property * " and then its work perfect.

thanks a lot!!!

$pc = Get-ADComputer -Filter * -Property * | Select-Object CN |
                      Out-GridView -OutputMode Single -Title 'Select one PC to rename'
$newname = Read-Host 'Please enter your new computer name: '
Rename-Computer -ComputerName $pc.CN -NewName $newname -DomainCredential amal-p\admin -Force -PassThru -Restart
Managing Consultant
Commented:
Just an efficiency comment -- you don't need "-Property *", you just need "-Property CN".

Retrieving one property instead of all properties should be noticeably faster and is certainly more efficient/performant.
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
Sorry, thought the CN attribute is retrieved by default.
Yes, please only add that single property, not "*" - in AD that can make a lot of difference for performance and resources, as there might be some methods called for extended attributes internally.
Get-ADComputer -Filter * -Property * | select -First 1 | gm is fine to check for available properties interactively, but aside from that, never use -property *, and try to avoid -filter * if you can apply a filter. E.g. a good filter would be -Filter 'Enabled -eq $true' to skip disabled computer accounts.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial