Joshua Wise
Joshua Wise

Reputation: 13

Filter Object Data before Export-CSV

I'm working on a powershell script that verifies a CSV with our AD, finds a list of accounts that are currently disabled, and then exports them to another CSV. I am currently able to read the CSV, compare, and export a list of all accounts with true/false flags regarding their status. I can also filter that output CSV using another script. IDEALLY, I would like to merge these into one script with only one output CSV. I'm just not sure how to do it.

I've tried moving the "where..." portion of script 2 into script 1 with no success.

Script 1:

Import-Csv C:\ServerScripts\Compare\students.csv | ForEach-Object {
New-Object -TypeName PSCustomObject -Property @{
    samaccountname = $_.samaccountname
    firstname = $_.firstname
    lastname = $_.lastname
    name = $_.name
    password = $_.password
    email = $_.email
    description = $_.description
    CAMPUS_ID = $_.CAMPUS_ID
    exist = [bool]($account=([adsisearcher]"(samaccountname=$($_.samaccountname))").findone())
    disabled = [bool]($account.properties.useraccountcontrol[0] -band 2)
}
} | Export-Csv C:\ServerScripts\Compare\output.csv -NoTypeInformation

Script 2:

Import-Csv C:\ServerScripts\Compare\output.csv | where {$_.disabled -ne "FALSE"} | Export-Csv C:\ServerScripts\Compare\disabled.csv -notypeinfo

Both scripts work independently, I just need a way to bring them together.

Upvotes: 0

Views: 546

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

Add your check in the first pipeline just before calling Export-Csv:

Import-Csv C:\ServerScripts\Compare\students.csv | ForEach-Object {
New-Object -TypeName PSCustomObject -Property @{
    samaccountname = $_.samaccountname
    firstname = $_.firstname
    lastname = $_.lastname
    name = $_.name
    password = $_.password
    email = $_.email
    description = $_.description
    CAMPUS_ID = $_.CAMPUS_ID
    exist = [bool]($account=([adsisearcher]"(samaccountname=$($_.samaccountname))").findone())
    disabled = [bool]($account.properties.useraccountcontrol[0] -band 2)
}
} |Where-Object {$_.disabled -eq $true} | Export-Csv C:\ServerScripts\Compare\output.csv -NoTypeInformation

Upvotes: 1

Related Questions