-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
1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Try removing the [array] part.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.