如何改善此AD更新Powershell脚本?

时间:2018-09-06 18:40:54

标签: powershell active-directory

几年前,我编写了此Powershell脚本,用于从CSV文件更新AD。我想尝试优化以更快地运行并且没有错误...但是我不确定从哪里开始/有什么可以改善它的。欢迎任何建议。

$users = Import-Csv -Path C:\Scripts\Employees.csv

foreach ($user in $users) {
Get-ADUser -ErrorAction SilentlyContinue -Filter "EmployeeID -eq '$($user.EmployeeID)'" -Properties * -SearchBase "ou=Logins,dc=domain,dc=com" |
    Set-ADUser -EmployeeNumber $($user."EmployeeNumber") -Department $($user."Department") -Title $($user."Title") -Office $($user."office") -StreetAddress $($user."Address") -City $($user."City") -State $($user."State") -PostalCode $($user."PostalCode") -Company $($user."Company") -OfficePhone $($user."telephone") -Mobile $($user."cell") -Fax $($user."Fax")

Get-ADUser -ErrorAction SilentlyContinue -Filter "EmployeeID -eq '$($user.EmployeeID)'" -Properties * -SearchBase "ou=Logins,dc=domain,dc=com" |
    Set-ADUser -Replace @{ExtensionAttribute1=($user.custom1); ExtensionAttribute2=($user.custom2); ExtensionAttribute3=($user.custom3); ExtensionAttribute4=($user.custom4)}
}

1 个答案:

答案 0 :(得分:0)

在这个主题上,我的价值仅2美分……许多人可以而且会对此采取不同的看法。 因此,总是乐于等待其他意见。

关于您的基准查询...

  

我想尝试优化以更快地运行并且没有错误

这是非常主观的事情。

  1. 优化意味着什么?
  2. 什么意思是使其运行得更快?

为什么您觉得它不是最佳的? 您为什么觉得速度不够快? 您使用了哪些指标或将其与哪些指标进行了比较?

因此,您需要确定以上内容对您意味着什么,然后才能采用可行的路线。因为这取决于您的操作以及操作方式,所以会很流畅。

参考文献:

How to speed up PowerShell operations on AD objects

Weekend Scripter: PowerShell Speed Improvement Techniques

Slow Code: Top 5 Ways to Make Your PowerShell Scripts Run Faster

Coding for speed

Why cant PowerShell run loops fast ?

所有所说的...

我想不出一个原因,为什么您对相同的getter数据使用两次Get-ADUser / Set-ADUser,只是您的setter不同。进行获取并设置一次。对于大型记录集/数据,循环速度很慢。请记住,ADDS对一次将返回的记录数施加了限制。如果您追求的不是默认值,则需要更改该广告设置/请求。如果它是一个大的记录集,最好对它进行分块和拆分,而不要对一个较小的记录集进行并行操作。看一下Parraller处理/工作流程/运行空间中的操作方法。