powershell - 使用文本文件遍历PowerShell命令

标签 powershell active-directory powershell-5.0

我有一个文本文件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/

相关文章:

Powershell 2 : Unable to suppress warning message

powershell - 将 cmdlet 的结果值存储在 Powershell 中的变量中

node.js - Windows 域中的 Linux 服务器上使用 NodeJS 进行 SSO

c# - Active Directory 用户和计算机的 LDAP 过滤器字符串 "find"对话

powershell - Powershell 5 中的类,需要帮助创建 $foo.bar.run()

powershell - Register-EventObject 在监听进程时不更新控制台

powershell - 在PowerShell中将字符串转换为int数组

winforms - Parent 如何在 System.Windows.Forms 中工作

c# - 抛出了 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' 类型的异常

windows - FuncOne() - 和 FuncTwo() 不工作