简体   繁体   English

根据 CSV 中的属性提取 AD 用户列表?

[英]Pulling a list of AD users based on attributes in a CSV?

I'm trying to use values in a CSV file as the variable in a Get-ADUser command.我正在尝试使用 CSV 文件中的值作为Get-ADUser命令中的变量。

Import-Module ActiveDirectory

$users = Import-Csv "C:\path\users.csv"

ForEach ($user in $users)
Get-ADUser -Filter { $user.sAmAccountName -SearchBase "ou=OU1,OU=OU2,DC=DC1,DC=DC2" }

The CSV has a header for samAccountName. CSV 有一个用于 samAccountName 的 header。

The error I'm getting is我得到的错误是

Get-ADUser : Error parsing query: '$user' Error Message: 'syntax error'

I'd point out a few additional issues:我要指出一些额外的问题:

With respect to the AD cmdlets -Filter parameter argument should be a string not a script block.关于 AD cmdlet -Filter参数参数应该是字符串而不是脚本块。 You can observe this in the help documentation.您可以在帮助文档中观察到这一点。 You can specify a script block and the cmdlet will convert it to a string, but that sometimes presents complications.您可以指定一个脚本块,cmdlet 会将其转换为字符串,但这有时会带来复杂性。

You are better off specifying the argument like:你最好指定如下参数:

Get-ADUser -Filter "$($user.sAmAccountName) -SearchBase 'ou=OU1,OU=OU2,DC=DC1,DC=DC2'"

That said, in this particular case you do not need the ForEach(..){..} loop.也就是说,在这种特殊情况下,您不需要ForEach(..){..}循环。 You can use property unrolling to simply pipe the samAccountName to Get-ADUser :您可以使用属性展开来简单地 pipe samAccountName 到Get-ADUser

$Users.samAccountName | Get-ADUser

This will not work in conjunction with the -SearchBase parameter, but I believe samAccountName is unique and should work in this manner.这不能与-SearchBase参数一起使用,但我相信 samAccountName 是独一无二的,应该以这种方式工作。 This is also true of using the -Identity parameter as discussed.如前所述,使用-Identity参数也是如此。 In fact, the piped approach is equivalent to the suggested use of -Identity parameter, the piped objects are bound to -Identity .实际上,管道方法相当于建议使用-Identity参数,管道对象绑定到-Identity However, you cannot site the array, unrolled or otherwise, as a directly specified argument to the -Identity parameter.但是,您不能将数组(展开或其他方式)定位为直接指定的参数给-Identity参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM