我正在尝试通过针对 CSV 文件中名为“OwnerEmail”(这是用户主体名称)的另一列查询 Active Directory 来填充 CSV 文件中的员工 ID 列。问题是owneremail 列中的用户并不都属于同一个域。如何同时查询 2 个域名?
引用表
这是我到目前为止所尝试过的。该脚本无法运行并且没有错误消息。任何想法
$Domains='us.domain.corp', 'uk.domain.corp'
$CSVImport |Select-Object @{
Name = "employeeID"
Expression = {
foreach($user in $CSVImport)
{
foreach($Domain in $Domains){
$user= (Get-ADUser -Filter "UserPrincipalName -eq '$($_.OwnerEmail)'" -Server $Domain -Properties 'SamAccountName').SamAccountName
}
}
}}, * |Select-Object employeeID, DepartmentNumber, OwnerEmail, @{Name="Costs"; Expression={"$ $($_.Cost)"}} | Export-Csv "$Env:temp/$OutputFile" -NoTypeInformation
最佳答案
How can I query 2 domains at one time?
没有必要这样做,您可以使用多线程同时查询两者,但这似乎有点过分了。我建议的是按域一次查询所有用户,下面的代码可能看起来非常复杂,但应该非常有效。有关详细信息,请参阅内嵌注释。
# Import the Csv
$CSVImport = Import-Csv path\to\thecsv.csv
# Create a LDAP Filter to query all users at once
# This filter would look like this for example:
# (|(<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e095938592b092898e838990818cae818d85dd94859394a08d81898cce838f8d" rel="noreferrer noopener nofollow">[email protected]</a>)(<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7b7d6b7c5e7c67606d677e6f62406f636b337a6b7d7a3c4e636f6762206d6163" rel="noreferrer noopener nofollow">[email protected]</a>))
$filter = "(|"
foreach($email in $CSVImport.OwnerEmail) {
if(-not [string]::IsNullOrWhiteSpace($email)) {
$filter += "(userPrincipalName=$email)"
}
}
$filter += ")"
# For each Domain, use the same filter and get all existing users
'us.domain.corp', 'uk.domain.corp' | ForEach-Object { $map = @{} } {
foreach($user in Get-ADUser -LDAPFilter $filter -Server $_) {
# and store them in a hashtable where
# the Keys are their `UserPrincipalName`
# and the Values are the attribute of interest (`SamAccountName`)
$map[$user.UserPrincipalName] = $user.SamAccountName
}
}
# Now we can simply use a calculated property with `Select-Object`
$CSVImport | Select-Object @{N='EmployeeID'; E={ $map[$_.OwnerEmail] }}, * |
Export-Csv "$Env:temp/$OutputFile" -NoTypeInformation
关于azure - 使用 PowerShell 查询多域中的 SamAccountName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74708674/