PSCustomObject list CSV only one column

79 Views Asked by At

Calling me a Powershell beginner would be giving me too much credit. I'm trying to read different Microsoft articles and StackOverflow threads, and they've been extremely helpful, but I've hit a point that's got me stumped. I'm trying to run through our AD OUs, checking every user in each OU, spitting out any user whose password is going to expire within 14~ days. I have a successful script that does just that, but now I'm trying to add extra columns into the CSV it spits out so I can have additional data to go off of like email address, password expiry date, etc. After much research this is what I've come up with, but it's spitting the two object properties (Email and PWExpires) into the same CSV column.

Any assistance is greatly appreciated!


$CutOffDate = (get-date).AddDays(-166).Date
$pwExpDate = $User.PasswordLastSet
$MaxCutOffDate = (get-date).AddDays(-365).Date
$pwExpList = [System.Collections.Generic.List[System.Object]]::new()

$OUs=
#deleted for posting


foreach($OU in $OUs) {
    $Users = Get-ADUser -filter * -SearchBase $OU -properties *
    foreach($User in $Users) {
        if(($User.PasswordLastSet -lt $CutOffDate) -and ($User.PasswordLastSet-gt $MaxCutOffDate) -and ($User.EmailAddress -notlike 'noreply*') -and ($User.EmailAddress -notlike '')) {
            $userObj = [PSCustomObject]@{
                Email = $User.EmailAddress
                PwExpires = $User.PasswordLastSet.AddDays(180)
            }
            $pwExpList.Add($userObj)
            #$pwExpList.Add($User.PasswordLastSet.AddDays(180))
        }
    }
}

$pwExpList | Out-File -FilePath G:\pwExpList2.csv
1

There are 1 best solutions below

0
Scepticalist On

Use Export-Csv and if you keep things simple rather than trying to make lists, you will make handling data much easier:

$CutOffDate = (get-date).AddDays(-166).Date
$pwExpDate = $User.PasswordLastSet
$MaxCutOffDate = (get-date).AddDays(-365).Date

# No need to pre-create an list object for your output - see below

$OUs=
#deleted for posting


$pwExpList = $OUs | ForEach-Object {
# Loop through all OUs
    Get-ADUser -filter * -SearchBase $_ -Properties * | ForEach-Object {
    # Loop through all found users
        If (($_.PasswordLastSet -lt $CutOffDate) -and ($_.PasswordLastSet-gt $MaxCutOffDate) -and ($_.EmailAddress -notlike 'noreply*') -and ($_.EmailAddress -notlike '')) {
            [PSCustomObject]@{
                Email = $_.EmailAddress
                PwExpires = $_.PasswordLastSet.AddDays(180)
            }
        }
    }
}

# Output to csv
$pwExpList | Export-Csv -Path C:\temp\output.csv -NoTypeInformation