0

I have a small script which retrieves the LastLogonTimestamp and the SAMAccount for all users in a particular OU in AD and converts the timestamp to a date and extracts just the date from the string. That part works fine. I then would like to output that to a CSV so it may be opened in Excel and be perfectly formated into columns and look all pretty.

I have tried ConvertTo-Csv and Export-Csv but have been uncuccessful. The problem is I am new to Powershell. This is my first script and I don't fully understand how this works. My script is probably terribly messy and illogical but it does the job so far.

Please help. Thanks.

$userlist = Get-ADUser -SearchBase "OU=IT,DC=whatever,DC=com,DC=au" -Filter * -Properties * | Select-Object -Property Name,LastLogonTimestamp,SAMAccountName | Sort-Object -Property Name

$userlist | ForEach-Object {
    $last = $_.LastLogonTimestamp;
    $ADName = $_.SAMAccountName;

    $tstamp = w32tm /ntte $last;
    if($tstamp.Length -lt "40"){}else
    {
        $ADDate = [DateTime]::Parse($tstamp.Split('-')[1]).ToString("dd/MM/yyyy")
        write-host $ADDate;
        write-host $ADName;
    }
}

1 Answer 1

4

You will have to create objects for each user and pipe those to the Export-CSV cmdlet:

$usersList | %{

# current logic

$user = new-object psobject
$user | add-member -membertype noteproperty -name LastLogon -value $last
$user | add-member -membertype noteproperty -name ADName -value $ADName
$user | add-member -membertype noteproperty -name ADDate -value $ADDate
$user
} | export-csv test.csv -notype

Alternative syntax for populating the object:

$properties = @{"LastLogon" = $last; "ADName" = $ADName; "ADDate" = $ADDate}
$user = new-object psobject -property $properties
Sign up to request clarification or add additional context in comments.

2 Comments

I've unvolontary downvoted your answer... probably because I was reading it with a smartphone and touched it. Can you edit it, so I can re-upvote it??
@Christian - Ah, I have done that :) Anyway, added the alternative syntax for creating objects.

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.