使用Powershell自动将用户图像上传到Active Directory



我有一个代码可以找到所有AD用户并将其与我们的照片文件夹进行比较。如果他们不是用户,则图像将被存档,如果找到图像,则不会发生任何反应。我想做的是,如果用户存在并且缩略图属性为空,则将图像上传到缩略图。事实证明,这比预期的要难。知道如何批量上传图像吗? 我的代码目前是

$usersWithoutImage = Get-ADUser -Filter * -properties thumbnailPhoto | ? {(-not($_.thumbnailPhoto))} 
| select Name
$repPics = (Get-childItem \web01rep-pics).basename
ForEach ($image in $usersWithoutImage){
if ($usersWithoutImage -eq $repPics){
$ADphoto = [byte[]](Get-Content $image -Encoding byte)
Set-ADUser $repPics -Replace @{thumbnailPhoto=$ADphoto}
}
}

第一步是添加一些日志记录,以便您知道是否以及何时命中某些代码分支。

$repPics = (Get-childItem \web01rep-pics).basename
Write-host "Found $($usersWithoutImage.Count) users without a photo"
ForEach ($image in $usersWithoutImage){
if ($usersWithoutImage -eq $repPics){
Write-host "Users name [$image] is in the users photo directory, uploading..."
$ADphoto = [byte[]](Get-Content $image -Encoding byte)
Set-ADUser $repPics -Replace @{thumbnailPhoto=$ADphoto}
}
else{
Write-Warning "Users name [$image] is NOT in the users photo directory, please update!!"
}
}

对你的代码进行一些分析会发现这一行......

if ($usersWithoutImage -eq $repPics){

这永远不会评估为真,因为比较没有意义。 您应该检查当前用户是否-in$repPics数组,而不是是否-equals,因为永远不会是这种情况。 我会这样重写它:

ForEach ($user in $usersWithoutImage){
if ($repPics -contains $user){

因此,您完成的代码将如下所示:

$repPics = (Get-childItem \web01rep-pics).basename
Write-host "Found $($usersWithoutImage.Count) users without a photo"
ForEach ($user in $usersWithoutImage){
if ($repPics -contains $user){
Write-host "Users name [$user] is in the users photo directory, uploading..."
$imagePath = ".$($user).png"
$ADphoto = [byte[]](Get-Content $imagePath -Encoding byte)
Set-ADUser $user -Replace @{thumbnailPhoto=$ADphoto}
}
else{
Write-Warning "Users name [$user] is NOT in the users photo directory, please update!!"
}
}

最后一件事是您需要更新行$imagePath =...以匹配您的文件路径和文件类型。

最新更新