我有一个文本文件test.txt
,其中包含一个OU列表,我需要计算每个OU中找到的用户数。
test.txt
:
"ou=MyOU1,dc=Mydomain,dc=net" "ou=MyOU2,dc=Mydomain,dc=net" "ou=MyOU3,dc=Mydomain,dc=net"
我将此传递给PowerShell中的命令:
Get-Content .\test.txt | Out-String | ForEach-Object {
(Get-ADUser -Filter * -SearchBase "$_").Count
}
我收到以下错误:
Get-ADUser : The supplied distinguishedName must belong to one of the following partition(s): 'DC=Mydomain,DC=net , CN=Configuration,DC=Mydomain,DC=net , CN=Schema,CN=Configuration,DC=Mydomain,DC=net , DC=ForestDnsZones,DC=Mydomain,DC=net , DC=DomainDnsZones,DC=Mydomain,DC=net'. At line:1 char:62 + ... ing) | ForEach-Object {(Get-ADUser -Filter * -SearchBase "$_").Count} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
但是,当我单独运行OU时,它可以工作。
PS> (Get-ADUser -Filter * -SearchBase "ou=MyOU1,dc=Mydomain,dc=net").Count
10782
注意:使用Out-String
不仅在代码中是不必要的,而且实际上会创建一个输出字符串,这会导致命令出现故障,因为ForEach-Object
只会被调用一次,带有多行字符串。
Get-Content
本身通过管道单独发送文本文件的行,这是你想要的:
Get-Content .\test.txt | foreach-object {
(get-aduser -filter * -searchbase $_).count
}
请注意,$_
已经是一个字符串,因此您无需将其括在"..."
中。
除此之外,如果文件中的行确实包含"..."
封闭的字符串,正如您的示例输入所示(可能不是,因为错误消息不反映它们),并且您无法修复文件本身,您必须删除这些双引号,因为它们成为传递给-SearchBase
的字符串的一部分:
Get-Content .\test.txt | foreach-object {
(get-aduser -filter * -searchbase ($_ -replace '"')).count
}