Renomeando computadores remotamente usando PowerShell 2.0


Hoje um grande amigo me perguntou como renomear computadores, em um dominio, usando o PowerShell 2.0 Se fosse o 3.0 eu logo falaria o cmdlet rename-computer, mas no 2.0 temos que usar WMI e uma dica que me custou algumas horas.

Usamos o metodo rename do cmdlet Get-WmiObject com a classe Win32_ComputerSystem, mas a dica é que temos que passar o parametro –authentication PacketPrivacy e também um usuário e senha no metodo Rename que tenha permissão para fazer esta operaçao (claaaaaaaaaaaaaaaaaaaaaaro)

Eu criei uma advanced function, claro que muito longe do que a rename-computer do 3.0 tem de recursos, mas quebra bem o galho :

Ela tem 3 parametros de entrada :

ComputerName – O nome antigo do computador

Newname – O Novo nome do computador

Credentials –Usuário e senha que podem fazer esta operaçao.

E ela retorna 3 propriedades :

HasSucceeded – True or False

OldComputername – O nome antigo

NewComputerName – O novo nome

 

Ela , como eu disse , é uma advanced function e você pode usar os commom parameters  -verbose e eu implementei suporte ao –whatif

Você só precisa digitar :

Rename-Computer20 -Computername Test50 -Newname Test51–verbose

E será pedido a você as credenciais :

Rename1

E a magica acontece :

Rename2

Como eu disse (de novo) é uma advanced function, então ela suporta o whatif :

Rename3

O codigo :

Function Rename-Computer20 {
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
[Parameter(Position=0,Mandatory=$true)][string]$ComputerName,
[Parameter(Position=1,Mandatory=$true)][string]$Newname,
[Parameter(Position=1,Mandatory=$False)][system.Management.Automation.PSCredential]$Credentials
)
try {

If (!($Psboundparameters.ContainsKey('Credentials'))) {
Write-Verbose 'Getting the User Name and Password'
$Credentials = Get-Credential -ErrorAction Stop
}

Write-Verbose "Testing the connection with computer $($Computername)"

try {
Test-Connection -ComputerName $Computername -ErrorAction Stop -Quiet |Out-Null

Write-Verbose "Checking if the new name $($Newname) exists !!!"

if (Test-connection -ComputerName $Newname -Quiet) {
Write-Error "Computer $($Newname) exists !!!"
} Else {

Write-Verbose "Test ok. Trying to rename Computer $($Computername) to $($Newname) "
$Hash = @{HasSucceeded = $False ; OldComputerName = "$($ComputerName)" ;NewComputerName = "$($NewName)"}

if ($PSCmdlet.ShouldProcess("Renaming Computer $($Computername) to $($Newname)")) {
if (!(Get-WmiObject Win32_ComputerSystem -ComputerName $Computername -Authentication PacketPrivacy -ErrorAction Stop).rename($Newname,[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credentials.Password)),$Credentials.UserName).ReturnValue) {
$Hash = @{HasSucceeded = $True ; OldComputerName = "$($ComputerName)" ;NewComputerName = "$($NewName)"}
Write-Warning "You must restart your computer for the changes to take effect"
}
Write-Output (New-Object PsObject -Property $hash)

}
}
} catch {
Write-Error "Connection with computer $($Computername) failed"
}
} catch {
Write-Error $error[0]
}
}

#Rename-Computer20 -Computername $args[1] -Newname $args[3] -whatif -verbose

 

Love Powershell hã ?

About Laerte Junior

Laerte Junior Laerte Junior is a SQL Server specialist and an active member of WW SQL Server and the Windows PowerShell community. He also is a huge Star Wars fan (yes, he has the Darth Vader´s Helmet with the voice changer). He has a passion for DC comics and living the simple life. "May The Force be with all of us"
This entry was posted in Algo que Esqueci de Categorizar. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s