powershell 如何使用PSCustomObjects对对象进行不变的更改?

nbnkbykc  于 2023-01-05  发布在  Shell
关注(0)|答案(1)|浏览(117)

我有两个表作为pscustomobjects,我尝试做一个SQL连接的等价操作,将一些属性添加回我需要读取的主对象。问题是我下面的代码在一个对象集合上运行了5个小时,大约有40,000个条目,仍然没有完成。我做错了什么吗?

$tableObj = import-csv ".\employeeIDsAndAttributes.csv"

"Getting AD data"
$directoryTable = Get-ADUser -Filter {(employeeid -like "*")} -Properties employeeid,name,samaccountname,distinguishedname | 
Select-Object employeeid,name,samaccountname,distinguishedname
"Finished getting AD data. Joining tables."

foreach ($changeRecordLine in $tableObj) {
    $changeRecordLine | add-member -NotePropertyName "Name" -NotePropertyValue ($directoryTable | Where-Object {($_.employeeid -eq $changeRecordLine.employeeID)} | Select-Object -ExpandProperty name) -Force
    $changeRecordLine | add-member -NotePropertyName "DN" -NotePropertyValue ($directoryTable | Where-Object {($_.employeeid -eq $changeRecordLine.employeeID)} | Select-Object -ExpandProperty distinguishedname) -Force
    $changeRecordLine | add-member -NotePropertyName "ParentDN" -NotePropertyValue ( $changeRecordLine.DN.substring($changeRecordLine.Name.length+4)) -Force
}

Excel通过使用vlookup让我没有问题地联接我的列,但这本应该也很快。
我试着运行上面的代码。当我取消这个过程时,我得到了$tableObj,并在Excel中检查了它,注意到一些条目已经被更改,但不是全部。我希望这个过程能相当快地完成。

k3bvogb1

k3bvogb11#

您的代码速度慢有两个主要原因,您使用Where-Object执行线性查找,而Where-Object本身速度很慢(这是PowerShell中过滤集合的最慢技术),但除此之外,您在每次循环迭代中执行2次线性查找,而本可以只执行一次

# lookup just once:
$lookUp = $directoryTable | Where-Object { $_.employeeid -eq $changeRecordLine.employeeID }
# then Name and DN are available to you:
$lookUp.Name
$lookUp.DistinguishedName

What you should use instead of a linear lookup is a structure meant specifically for fast lookups:

$tableObj = Import-Csv ".\employeeIDsAndAttributes.csv"
$map = @{}

# `name, samaccountname, distinguishedname` are already default properties
# no need to include them in `-Properties`
foreach($user in Get-ADUser -Filter "EmployeeId -like '*'" -Properties employeeid) {
    $map[$user.employeeid] = $user
}

foreach($changeRecordLine in $tableObj) {
    $value = $map[$changeRecordLine.employeeid]
    $props = $changeRecordLine.PSObject.Properties

    $parentDN = try {
        $changeRecordLine.DN.SubString($changeRecordLine.Name.Length + 4)
    }
    catch { }

    # `Add-Member` adds overhead even though this is the least of your code's issues,
    # adding `NoteProperties` to your objects by accessing
    # the object's PSObject Properties and adding them manually is faster
    $props.Add([psnoteproperty]::new('Name', $value.Name))
    $props.Add([psnoteproperty]::new('DN', $value.DistinguishedName))
    $props.Add([psnoteproperty]::new('ParentDN', $parentDN))
}

相关问题