【问题标题】:PowerShell Active Directory Compare with Text filePowerShell Active Directory 与文本文件比较
【发布时间】:2017-02-23 05:20:46
【问题描述】:

我正在尝试制作一个脚本,将文本文件中的资产标签列表与 AD 中的计算机名称进行比较,并生成描述。稍后将其导出为 CSV。到目前为止,虽然代码确实有效,但它会给出以下错误消息。我们在 AD 中的计算机以 L 或 D 开头,说明它是笔记本电脑还是台式机,但我们收到的列表中不包含 L 或 D,这就是为什么你看到我把“L”+“D”在前面。有更好的方法吗?

代码:

    Import-Module ActiveDirectory

        foreach ($line in Get-Content ComputerNames.txt)  {
            if($line -match $regex) {
                $laptop = "L" + $line
                $desktop = "D" + $line 
                get-ADComputer  $laptop  -Properties * |select Description  
                #get-ADComputer $desktop -Properties * |select Description -ErrorAction Ignore           }  

}

错误:

get-ADComputer : Cannot find an object with identity: 'LD7MWQ12' under: 'DC=ap,DC=o-i,DC=intra'.
At line:9 char:9
+         get-ADComputer  $laptop  -Properties * |select Description
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (LD7MWQ12:ADComputer) [Get-ADComputer], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: 'LD7MWQ12' under: 'DC=ap,DC=o-i,DC=intra'.,Microsoft.ActiveDirectory.Management.Com 
   mands.GetADComputer

【问题讨论】:

  • 如果您手动检查该对象是否存在,那根本就是找不到对象“LD7MWQ12”?
  • 不,它不存在,因为资产 D7MWQ12 实际上以 D(全名 DD7MWQ12)开头。有没有办法忽略错误消息,或者完全绕过它并搜索以字母 D 或 L 开头的资产?
  • 要绕过错误,您可以使用stackoverflow.com/questions/8388650/…

标签: powershell


【解决方案1】:

可能是一种更有效的方法但是以下方法有效:

   Import-Module ActiveDirectory

    foreach ($line in Get-Content ComputerNames.txt)  {
        Get-ADComputer -Filter * -Property Description | Where {$_.samaccountname -Like "*$line"} | select Description
    }

对于computernames.txt 对象中的每一行,它将查找类似于$line 变量的AD 对象,然后选择该对象的描述

【讨论】:

    【解决方案2】:

    缓慢的一点将是到 AD 的网络链接,如果可能的话,你真的只想这样做一次。除非您在 AD 中拥有大量计算机,否则最好将所有计算机拉下来,然后在本地与文本文件进行比较。

    另外,如果你是从 AD 中提取信息,不要带太多,浪费了网络流量和内存开销,所以不要使用 Properties *,只需在描述中添加即可

    Import-Module ActiveDirectory
    
    # AD query which will get all computers with names starting D or L
    $ADFilter = "Name -like 'D*' -or Name -like 'L*'"
    $ADComputers = Get-ADComputer -filter $ADFilter -Properties Description | Select Name, Description
    
    $NamesFromFile = Get-Content ComputerNames.Txt
    
    # Filter the AD Computers where the name without the first character is
    # mentioned in the file
    $ADComputers | Where-Object { $_.Name.SubString(1) -in $NamesFromFile } | Export-Csv -NoTypeInformation out.csv
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2015-04-29
      • 1970-01-01
      相关资源
      最近更新 更多