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)?
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
$exportCsv = @()
Import-Csv C:\Users\drives.csv | Foreach-Object{
$user = ([ADSISEARCHER]"(samaccountname=$($_.SamAccountName))").FindOne()
if($user)
{
$exportCsv += New-Object -TypeName PSObject -Property @{
SamAccountName = $user.SamAccountName
IsDisabled = $user.GetDirectoryEntry().InvokeGet('AccountDisabled')
}
}
else
{
Write-Warning "Can't find user '$($_.SamAccountName)'"
}
}
$exportCsv | Export-Csv -Path $myOtherCsvFilePath
Here you add a Powershell array of PSObjects to another CSV file
You should change your Code a bit.
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
{
New-Object -TypeName PSObject -Property @{
SamAccountName = $user.SamAccountName
IsDisabled = 'not found'
}
}
} | export-csv myNew.csv -Append -NotypeInformation
Now you wont lose object info by piping.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.