How to export the last login details of all users in a Windows server using Powershell

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.
windows_last_login

How to display a pop up message in a remote computer using powershell

In my daily work, there are times which I need to contact a user who is using a particular PC, but they don’t respond. Mostly, I need to contact them to inform about something, or get them to reboot, or install something etc. There are some cases which it is not possible, such as :

  • They use a generic account which is shared, so we can’t find who exactly is using that PC
  • They are logged off from IM
  • They don’t respond to IM or just ignore them.

In these kind of cases, it is easier if we have some way to forcefully push a message to the PC. I found an easy solution from internet that can do this in every computer that you have admin access.

Open a text editor and add the following in it, then save it with .ps1 extension.

Function remote_message{

$server = read-host -prompt ‘Input PC name’;
$message = read-host -prompt ‘Enter the message’;

Invoke-WmiMethod -Class win32_process -ComputerName $server -Name create -ArgumentList¬† “c:\windows\system32\msg.exe * $message” }

remote_message

To run this, open powershell, then navigate to the saved location and run. And follow the input prompt.

remote_message

No matter who is logged in the remote PC, they will get the message pop up on top of all their windows.

remote_message_2