2017-02-23 71 views
0

我想製作一個腳本,將文本文件中的資產標籤列表與AD中的計算機名稱進行比較,並生成說明。將其導出爲CSV將在稍後進行。儘管如此,雖然代碼確實有效,但它會提供以下錯誤消息。我們在AD中的計算機以L或D開頭,表明它是筆記本電腦還是桌面計算機,但我們收到的列表中不包含L或D,這就是爲什麼您看到我將「L」+「D」在前面。有沒有更好的方法來做到這一點?PowerShell活動目錄與文本文件比較

代碼:

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 
+0

如果您手動檢查該對象是否存在,那麼根本找不到對象「LD7MWQ12」? –

+0

不,它不存在,因爲資產D7MWQ12實際上以D(全名DD7MWQ12)開頭。有沒有辦法忽略錯誤信息,或者完全繞過它並搜索以字母D或L開頭的資產? – ilovetaufu

+0

繞過錯誤,你可以使用http://stackoverflow.com/questions/8388650/powershell-how-can-i-stop-errors-from-being-displayed-in-a-script –

回答

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對象,然後選擇該對象的描述

+0

謝謝拉奇!它現在有效! – ilovetaufu

0

慢位將成爲AD的網絡鏈接,您真的只想這樣做一次if可能。除非在AD中有大量的計算機,否則最好將所有計算機拉下來,然後在本地將其與文本文件進行比較。

而且如果你從AD中提取信息,不要把比你需要更多的網絡流量和內存開銷被浪費,所以不是屬性*,只需添加在說明

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