加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

如何将照片导入AD中

(2019-01-29 10:18:43)
照片格式要求:1.照片大小不要超过大小不要超过30KB;2.照片尺寸一般不超过96X96。因为这些照片是存在AD数据库中的,如果太大的话,会导致AD的数据库增大,从而影响AD之间的复制。
以下是几种方法将照片导入AD数据库:

1、powershell脚本修改

脚本1:

$SAMName=Read-Host "Enter a username"
 
      $root = [ADSI]'GC://dc=uc,dc=local'
      $searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectClass=user)(sAMAccountName=$SAMName))"
$user = $searcher.findall()
$userdn = $user[0].path
$userdn = $userdn.trim("GC")
$userdn = "LDAP" + $userdn
 
function Select-FileDialog
{
    param([string]$Title,[string]$Directory,[string]$Filter="All Files (*.*)|*.*")
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
    $objForm = New-Object System.Windows.Forms.OpenFileDialog
    $objForm.InitialDirectory = $Directory
    $objForm.Filter = $Filter
    $objForm.Title = $Title
    $objForm.ShowHelp = $true
    $Show = $objForm.ShowDialog()
    If ($Show -eq "OK")
    {
        Return $objForm.FileName
    }
    Else
    {
        Write-Error "Operation cancelled by user."
    }
}
 
$photo = Select-FileDialog -Title "Select a photo" -Directory "%userprofile%" -Filter "JPG Images (*.jpg)|*.jpg"
 
$user = [ADSI]($userdn)
[byte[]]$file = Get-Content $photo -Encoding Byte
 
# clear previous image if exist 
$user.Properties["thumbnailPhoto"].Clear()
 
# write the image to the user's thumbnailPhoto attribute by converting the byte[] to Base64String 
$user.Properties["thumbnailPhoto"].Add([System.Convert]::ToBase64String($file))
 
# commit the changes to AD 
$user.CommitChanges()
 

 脚本2:

#Add-ADPhoto   Powershell v1 compatibile script for updating
#user thumbnailphoto attribute.  Resizes input photo to recommended
#dimensions and size.  Only updates for the currently logged in user.
#This is a script for user self service.
 
#Author: Nathan Linley
#Site: http://myitpath.blogspot.com
 
$infile = $args[0]
$aspect = $args[1]
 
function usage {
        write-host "Usage: Add-ADPhoto filename [aspect]"
        write-host "   Provide the name of an image file in your current directory."
        write-host "   If you wish to preserve the aspect ratio of the image, type"
        write-host "   1 after your file name.  Images are resized to the recommended"
        write-host "   96x96, converted to JPG and set to 70% quality to limit size."
        exit 
 
}
$imagefile = (pwd).path + "\" + $infile
$imagefileout = (pwd).path + "\adout.jpg"
 
##############################################################################
#Check to see if the argument for filename was provided, and that it exists###
##############################################################################
if ([string]::isnullorempty($infile) -or -not (test-path $imagefile)) {
        &usage
}
 
 
###############################
#Remove any old converted file#
###############################
if (test-path $imagefileout) {
        del -path $imagefileout -ErrorAction "silentlycontinue"
}
 
$Image = New-Object -ComObject Wia.ImageFile
$ImageProcessor = New-Object -ComObject Wia.ImageProcess
 
 
##########################################################
#Try loading the file, if its not an image this will fail#
##########################################################
$Image.LoadFile($ImageFile)
 
if (-not $?) { &usage }
 
 
#############################################################
#Create filters, set aspect ratio setting, change dimensions#
#to max 96pixels, convert to JPG and set quality            #
#############################################################
$Scale = $ImageProcessor.FilterInfos.Item("Scale").FilterId
$ImageProcessor.Filters.Add($Scale)
$Qual = $ImageProcessor.FilterInfos.Item("Convert").FilterID
$ImageProcessor.Filters.Add($qual)
 
if ([string]::isnullorempty($aspect) -or [string]$aspect -ne "1") {
        $ImageProcessor.Filters.Item(1).Properties.Item("PreserveAspectRatio") = $false
} else {
        $ImageProcessor.Filters.Item(1).Properties.Item("PreserveAspectRatio") = $true
}
 
$ImageProcessor.Filters.Item(1).Properties.Item("MaximumHeight") = 96
$ImageProcessor.Filters.Item(1).Properties.Item("MaximumWidth") = 96
$ImageProcessor.Filters.Item(2).Properties.Item("FormatID") = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
 
####################################################################
#Drop image quality until it meets the size recommendation of 10kb #
####################################################################
$quality = 80
do {
        Remove-Item -path $imagefileout -ErrorAction "silentlycontinue"
        $ImageProcessor.Filters.Item(2).Properties.Item("Quality") = $quality
        $Image = $ImageProcessor.Apply($Image)
        $Image.SaveFile($ImageFileOut)
        [byte[]]$imagedata = get-content $imagefileout -encoding byte
        $quality -= 10
} while ($imagedata.length -gt 10kb)
 
 
#####################################################################
#Find domain, and Account distinguished name.  Open user object, add#
#thumbnailphoto data and save.
#####################################################################
$de = new-object directoryservices.directoryentry("LDAP://" + $env:logonserver.substring(2))
$ds = new-object directoryservices.directorysearcher($de)
$ds.filter = "(&(objectclass=user)(samaccountname=" + $env:username + "))"
$myaccount = $ds.findone()
$de = new-object directoryservices.directoryentry($myaccount.path)
$de.properties["Thumbnailphoto"].clear()
$de.properties["Thumbnailphoto"].add($imagedata) |out-null
$de.setinfo()
Write-Host "Photo has been uploaded"

 

2、vbscript脚本修改

我AD里面的用户名字是张三,那么照片也是张三。

AD里面用户的名称为张三,而AD属性里面对应名称字段的值为name,要以这个为准。因为我们一会脚本搜索的属性也是这个name属性。

照片就非常简单了,用户的名字为文件名。

 

Const ForReading = 1
 
'图片存的目录 
InDir = "C:\photo" 
Set fso = CreateObject("Scripting.FileSystemObject") 
set oIADS = GetObject("LDAP://RootDSE") 
strDefaultNC = oIADS.Get("defaultnamingcontext") 
Set theConn = CreateObject("ADODB.Connection") 
theConn.Provider = "ADsDSOObject" 
theConn.Open "ADs Provider" 
Set theCmd  = CreateObject("ADODB.Command") 
theCmd.ActiveConnection = theConn 
Set objRecordSet = CreateObject("ADODB.Recordset") 
For Each tFile In fso.GetFolder(InDir).Files 
    tName = tFile.Name 
    tName = Left(tName, InStrRev(tName,".")-1) 
      strQuery = " & strDefaultNC & ">;" & "(&(objectClass=person)(name=" & tName & "));name,adspath;subtree" 
    theCmd.CommandText = strQuery 
    Set objRS = theCmd.Execute 
    If objRS.RecordCount = 0 Then 
      MsgBox "Can't find account for " & tName 
    Else 
      Set objUser = GetObject(objRS("adspath")) 
      ObjUser.Put "thumbnailPhoto", ReadByteArray(tFile.Path) 
      ObjUser.SetInfo 
    End If 
Next 
 
 
Function ReadByteArray(strFileName) 
    Const adTypeBinary = 1 
    Dim bin 
    Set bin = CreateObject("ADODB.Stream") 
    bin.Type = adTypeBinary 
    bin.Open 
    bin.LoadFromFile strFileName 
    ReadByteArray = bin.Read 
End Function

3、C#代码修改

DirectoryEntry container = new DirectoryEntry(LDAP_URI + USERS_DIR);
DirectoryEntry user = container.Children.Add("cn=" + username, "user");
 
// Set other property's of the user object:
//// user.Properties ["xxx"].Value = "yyy";
//// ...
 
byte [] buffer;
FileStream fileStream = new FileStream(@"c:\photo.jpg", FileMode.Open, FileAccess.Read);
 
try {
    int length = (int) fileStream.Length;  // get file length
    buffer = new byte [length];            // create buffer
    int count;                             // actual number of bytes read
    int sum = 0;                           // total number of bytes read
 
    // read until Read method returns 0 (end of the stream has been reached)
    while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
        sum += count;  // sum is a buffer offset for next reading
}
 
finally {
    fileStream.Close();
}
 
user.Properties ["thumbnailPhoto"].Value = buffer;
 
user.CommitChanges();


原文摘自:https://www.cnblogs.com/love007/archive/2012/08/14/2637931.html 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有