根据用户名移动计算机账号

上周客户提出了一个要求,将Computers里面的计算机账号移动到相应的OU下,由于数量比较大,采用脚本。
在客户环境中计算机账号名和用户名一致。这样问题处理就比较简单了,先获取此OU下面的用户名,然后和Computers计算机账号名一一匹配,如果一致,则移动此计算机账号到对应OU下。
自定义powershell命令SearchMove-ADComputer
使用方法:
将与“ou=test,dc=contoso,dc=com”下用户名一致的计算机账号移动到“ou=computers,ou=test,dc=contoso,dc=com” 下
SearchMove-ADComputer –SearchBase “ou=test,dc=contoso,dc=com” –TargetPath “ou=computers,ou=test,dc=contoso,dc=com”

1.	将以下PS代码保存为.PS1文件
2.	在Powershell Console中运行此文件
3.	Import-Module ActiveDirectory
4.	运行SearchMove-ADComputer指令

PS代码如下:

function SearchMove-ADComputer 
        ([string] $SearchBase,
         [string] $TargetPath)
{
$count = 0
$users = Get-ADUser -Filter *  -SearchBase $SearchBase |Select-Object samaccountname
#SearchBase后面的参数需要改为自己环境的域名
$computers = Get-ADComputer -Filter * -SearchBase "cn=computers,dc=contoso,dc=com" |Select-Object DistinguishedName,name
$result = @()
for ($index = 0; $index -le ($computers.Length - 1); $index++) 
{
    foreach ($item in $users)
    {
    
        if($item.samaccountname -contains ($computers[$index].Name) -eq $true )
        {
          $ComputerName = New-Object -TypeName PSObject
          $ComputerName | Add-Member NoteProperty ComputerName $computers[$index].Name
          $ComputerName | Add-Member NoteProperty DN $computers[$index].DistinguishedName
          $result += $ComputerName   
        }

    }
}

Start-Sleep 2

if($result.count -eq 0)
{
    Write-Host "没有查询出相关账号,请更改查询条件" 
} 
else 
{
    #移动到Computers OU下
    foreach ($computerid in $result) 
    {
       Move-ADObject -Identity $computerid.DN -TargetPath $TargetPath 
        $count++
    }
    Write-Host "共计移动"$count"个计算机账号"  -ForegroundColor Green 
}
  
}

 

posted @ 2013-12-24 08:43  motools  阅读(747)  评论(0编辑  收藏  举报