Heath Hackett Heath Hackett - 3 months ago 20
PowerShell Question

Powershell script that imports from CSV, checks AD account status, then exports to CSV

I am writing a Powershell script to take a CSV file of Active Directory accounts, validate each account, and write the validation status back to a separate CSV file. I need assistance in writing the CSV; I've looked at the Export-Csv cmdlet but I'm a little confused how it would work when I am already importing a CSV. Here is my code so far:

Import-Csv C:\Users\drives.csv | Foreach-Object{

$user = ([ADSISEARCHER]"(samaccountname=$($_.SamAccountName))").FindOne()

if($user)
{
New-Object -TypeName PSObject -Property @{
SamAccountName = $user.SamAccountName
IsDisabled = $user.GetDirectoryEntry().InvokeGet('AccountDisabled')
}
}
else
{
Write-Warning "Can't find user '$($_.SamAccountName)'"
}


}

Any thoughts on how to export both the account name (which is being imported from one CSV) and the account status (which my current script provides)?

Answer

Here is one possibility - untested, but it is intended to illustrate the export-csv. All standard caveats apply :)

$resultList = @()
Import-Csv C:\Users\drives.csv -header("SamAccountName") | Foreach-Object{

   $user = ([adsisearcher]"(samAccountName=$($_.SamAccountName))").FindOne()

   $resultList += New-Object -TypeName PSObject -Property @{
           SamAccountName = $_.SamAccountName
           IsDisabled = if ($user) { 
                            $user.GetDirectoryEntry().InvokeGet('AccountDisabled') 
                        } else {
                            "User not found."
                        }
       }

}

$resultList | export-csv -Path c:\users\driveresult.csv -NoTypeInformation
Comments