So one of our clients want to get a monthly report on the last login details of all users in the Windows servers in our environment. So we came up with this powershell script which is scheduled to run end of every month. This will extract the data, and upload them to an S3 bucket. It makes use of awscli for uploading to s3. We can even include SNS notification, but right now it is not implemented.
Below is the script:
Disclaimer : I do not know if this is the best way to do it just like all my other scripts, but this works [ At least for me ]
$currentMonth = Get-Date -Format MM $currentYear = Get-Date -UFormat %Y $hostname = hostname $filename = $currentYear+""+$currentMonth+""+$hostname+"_login.csv" $([ADSI]"WinNT://$env:COMPUTERNAME").Children | where {$_.SchemaClassName -eq 'user'} | select @{l='name';e={$_.name}},@{l='LastLogin';e={$_.lastlogin}} | export-csv C:/temp/$filename (gc C:/temp/$filename) -replace (gc C:/temp/$filename)[0],"" | sc C:/temp/$filename -Force (gc C:/temp/$filename) -replace (gc C:/temp/$filename)[1],"" | sc C:/temp/$filename -Force (gc C:/temp/$filename) | ? {$_.trim() -ne "" } | set-content C:/temp/$filename aws s3 cp C:/temp/$filename s3://YourBucket/$currentYear/$currentMonth/
This will create a csv file in the following format.