我需要传入一个用户列表,并使用姓名,SamAccountName,电子邮件返回CSV
我的输入CSV如下:
"John Doe"
"Jane Doe"
这是我正在使用的当前代码。我不确定问题是什么。用户实际上确实存在于指定的“DC”...
Import-Module ActiveDirectory
Function Get-ADUsersDetailsCSV
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$True,Position=1)]
[String]$InCSV,
[Parameter(Mandatory=$True)]
[String]$OutCSV
)
If($InCSV)
{
If(Test-Path -Path $InCSV)
{
$USERS = Import-CSV $InCSV -Header Name
$USERS|Foreach{Get-ADUser $_.Name -Properties * |Select Name, SAMAccountName, mail}|Export-CSV -Path $OutCSV
} #End Test that the files exist
Else
{
Write-Warning "Cannot find path '$InCSV' because it does not exist."
}
} #End Ensure Input and Output files were provided
} #End Function Get-UsersDetailsCSV
这是错误:
Get-ADUser : Cannot find an object with identity: 'John Doe' under: 'DC=blah,DC=com'.
At U:\data\GetADUserInfo PS Script\GetADUsersDetailsCSV.psm1:19 char:28
+ $USERS|Foreach{Get-ADUser $_.Name -Properties * |Select Name, SAMAcc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Name:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'John Doe' under: 'DC=blah,DC=com'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
答案 0 :(得分:1)
这不起作用的原因是-Identity
cmdlet使用的Get-ADUser
参数是在SamAccount
属性上搜索AD,而不是Name
属性来检索用户。因此,寻找" John Doe"将无法正常工作,而是期望您使用SamAccount名称进行搜索:" JDoe"
要按名称搜索,您必须按名称过滤结果:
Get-ADUser -Filter {Name -eq "John Doe"}
因此,您的代码变为:
$USERS|Foreach{Get-ADUser -Filter {Name -eq $_.Name} -Properties * |Select Name, SAMAccountName, mail}|Export-CSV -Path $OutCSV
答案 1 :(得分:1)
如果您运行Get-Help Get-ADUser,您将找到Identity参数的此描述:
-Identity <ADUser>
Specifies an Active Directory user object by providing one of the following property values. The identifier in parentheses is the LDAP display name for the attribute.
Distinguished Name
Example: CN=SaraDavis,CN=Europe,CN=Users,DC=corp,DC=contoso,DC=com
GUID (objectGUID)
Example: 599c3d2e-f72d-4d20-8a88-030d99495f20
Security Identifier (objectSid)
Example: S-1-5-21-3165297888-301567370-576410423-1103
SAM account name (sAMAccountName)
Example: saradavis
请注意,Name不是它接受的身份之一。 Name不是AD中的索引属性,因为它不保证是唯一的。它可能在您的域中,但AD不知道。要通过任何其他属性获取用户,您需要使用过滤器,因此您的脚本看起来像这样(为了便于阅读,我可以自由折叠)
$USERS | Foreach{
Get-ADUser -filter "Name -eq '$($_.name)'" -Properties mail |
Select Name, SAMAccountName, mail}|
Export-CSV -Path $OutCSV
另请注意,Name和SAMAccountName是Get-ADUser将返回的常见属性,因此您必须指定的唯一其他属性是Mail。
我认为这会照顾额外的要求,但我没有测试它:
$USERS | Foreach{
$getuser =
Get-ADUser -filter "Name -eq '$($_.name)'" -Properties mail |
Select Name, SAMAccountName, mail
if ($getuser) {$getuser}
else {[PSCustomObject]@{Name=$_;SAMAccountName='Not found';mail=$null}}
} |
Export-CSV -Path $OutCSV