-2

previously I tried to make a powershell script to compared asset tags from a text files with computer names in AD, that was successful. However, when an asset isn't found in AD it just skips through that line and moves on to the next. The asset that cannot be found is not exported into the CSV file.

Is there a way to get it to print in the CSV file the missing Asset, along with a message like "Asset not found" next to the asset tag? I tried using this line but all that does is add spaces in between the lines.

if ($_.samaccountname -notlike "*$line*") {"Asset does not exist in AD"}

Code:

Import-Module ActiveDirectory

   [Array]$Collection = foreach($line in Get-Content H:\AssetNames.txt)  {
        Get-ADComputer -Filter * -Property Description | Where {$_.samaccountname -Like "*$line*"} | Select Name, Description
        #if ($_.samaccountname -notlike "*$line*") {"Asset does not exist in AD"}
    }

$Collection | Export-Csv C:\test.csv -NoTypeInformation
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
ilovetaufu
  • 25
  • 4
  • 2
    Query AD and Export to CSV comes up all the time. There's enough in the combination of these to do all the things you want ... http://stackoverflow.com/q/25789067/478656 and http://stackoverflow.com/q/22303219/478656 and http://stackoverflow.com/q/4381943/478656 and http://stackoverflow.com/q/40930461/478656 and http://stackoverflow.com/q/19164485/478656 and http://stackoverflow.com/q/36292356/478656 and http://stackoverflow.com/q/38407983/478656 and http://stackoverflow.com/q/41573219/478656 – TessellatingHeckler Mar 17 '17 at 02:28

1 Answers1

0

Your issue is that you are excluding Assets that don't match in your Get-ADComputer filter, so then you have no way of knowing when they haven't matched. If you do this to a variable, then you can check:

Import-Module ActiveDirectory

   [Array]$Collection = foreach($line in Get-Content H:\AssetNames.txt)  {
        $Match = Get-ADComputer -Filter * -Property Description | Where {$_.samaccountname -Like "*$line*"} | Select Name, Description
        if (!$Match) {
            "Asset $($_.samaccountname) does not exist in AD" | Out-File -FilePath "ErrorLog.txt" -Append
        } else {
            Write-Output $Match
        }
    }

$Collection | Export-Csv C:\test.csv -NoTypeInformation
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • Hey Mark, sorry for the late response. Just tried this but the write-output isn't writing the missing assets into the CSV file, any assets that can't be found in AD is replaced by an empty line in the CSV file. – ilovetaufu Mar 20 '17 at 07:16
  • Try removing the [array] part. – Mark Wragg Mar 20 '17 at 07:18
  • Tried that, it is still the same. If I let it write to a separate text file the missing assets do show up in that text file however. – ilovetaufu Mar 20 '17 at 07:31