我有一个文本文件test.txt
,其中包含一个OU列表,我需要在其中计算每个OU中发现的用户数。test.txt
:
"ou=MyOU1,dc=Mydomain,dc=net" "ou=MyOU2,dc=Mydomain,dc=net" "ou=MyOU3,dc=Mydomain,dc=net"
I am passing this to command in 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
However, when I run the OU individually, it works.
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
}
请注意,
$_
已经是一个字符串,因此您不必将其包含在"..."
中。除此之外,如果文件中的行确实包含
"..."
括起来的字符串,如示例输入所示(可能不是,因为错误消息没有反射(reflect)出它们),并且您无法修复文件本身,则必须删除这些双引号,否则它们将成为传递给-SearchBase
的字符串的一部分:Get-Content .\test.txt | foreach-object {
(get-aduser -filter * -searchbase ($_ -replace '"')).count
}
关于powershell - 使用文本文件遍历PowerShell命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52265351/