Tag: Powershell

User Tracking Logon Script

The following script will help you keep track of which machines are being logged into. The script will find the logged in user and it will retrieve basic information about the machine that was used to log in. The logons will be tracked in a CSV that is created daily by the script. To implement this, you can add the script to your GPO and have it run during logon.

The example saves the CSV in the C drive but you can save it anywhere by specifying the directory name in the $directory variable.

#Gets information for the spreadsheet
$username = $env:USERNAME
$computername = $env:COMPUTERNAME
$ipv4 = Test-Connection -ComputerName (hostname) -Count 1 | foreach { $_.ipv4address } 
$ipv6 = Test-Connection -ComputerName (hostname) -Count 1 | foreach { $_.ipv6address } 
$computermodel = get-wmiobject win32_computersystem | foreach { $_.model } 
$serial = get-wmiobject win32_bios | foreach { $_.serialnumber } 
$timeformat='MM-dd-yyyy hh:mm:ss tt'
$time = (Get-Date).ToString($timeformat)
$action = 'Logon'

#Specifies filename, and directory
$directory = "c:\"
$filedate = 'MM-dd-yyyy'
$filename = 'CompInfo' + ' ' + $(Get-Date).ToString($filedate)
$file = "$filename.csv"

#Creates custom table and sorts the information
$table=  New-Object –TypeName PSObject -Property @{
            'Date/Time' = $time
            'Username' = $username
            'ComputerName'= $computername
            'IPv4 Address' = $ipv4
            'IPv6 Address' = $ipv6
            'Model' = $computermodel
            'Serial' = $serial
            'Notes/Action' = $action
} | Select date/time, username, computername, 'IPv4 Address', 'IPv6 Address', model, serial, notes/action 

#Checks if CSV has already been created for the day.
if (Test-path "$directory\$file") {
    
    import-csv -Path "$directory\$file" > null
    $table | Export-Csv -NoTypeInformation -Append -Path "$directory\$file"

}

else{ 
    $table | Export-Csv -NoTypeInformation -Path "$directory\$file" 
}