Reputation: 25
I am trying to make a script that compares a list of asset tags in a text file with the computer names in AD, and generate the Description. Exporting it to CSV will come later. As of now though, while the code does work, it gives the following error message. Our computers in AD starts with either L or D, which states whether it's a laptop or desktop, but the list we receive does not contain the L or D in it, which is why you see me putting the "L" + "D" at the front. Is there a better way of doing this?
Code:
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 }
}
Error:
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
Upvotes: 0
Views: 473
Reputation: 29048
The slow bit is going to be the network link to AD, you really only want to do that once if possible. Unless you have huge numbers of computers in AD, it would be better to pull down all the computers and then compare them locally against the text file.
Also if you're pulling information from AD, don't bring any more than you need, the network traffic and memory overhead is wasted, so instead of Properties *, just add in the description
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
Upvotes: 0
Reputation: 1261
Probably a more efficient way to do this But the below works:
Import-Module ActiveDirectory
foreach ($line in Get-Content ComputerNames.txt) {
Get-ADComputer -Filter * -Property Description | Where {$_.samaccountname -Like "*$line"} | select Description
}
For every line in the computernames.txt
object it will go and find the AD Object that is like the $line
variable and then select the Description for that object
Upvotes: 1