Skip to content

Instantly share code, notes, and snippets.

@jamil666
Created March 16, 2020 10:01
Show Gist options
  • Save jamil666/60b31fbb6ac84cea08ed059eaf49b5c1 to your computer and use it in GitHub Desktop.
Save jamil666/60b31fbb6ac84cea08ed059eaf49b5c1 to your computer and use it in GitHub Desktop.
Needed modules: PSSQlite, Quest Active Directory
Import-Module PSSQLite
Add-PSSnapin Quest.ActiveRoles.ADManagement
# Database path
$Database = "C:\report\UsersLastLogon.SQLite"
$Query = "CREATE TABLE IF NOT EXISTS UsersLastLogon (
Username TEXT,
Computername TEXT,
LastLogon TEXT)"
#SQLite will create UsersLastLogon.SQLite database
Invoke-SqliteQuery -DataSource $Database -Query $Query
# Empty database
Invoke-SqliteQuery -DataSource $Database -Query "DELETE FROM UsersLastLogon;"
$cred = Get-Credential -Credential 'domain\username'
# Select only Windows 10 computers
$Comps = Get-QADComputer -OSName '*10*' -SizeLimit 0
foreach($comp in $comps)
{
$UserInfo = Get-WmiObject –ComputerName $comp.Name –Class Win32_ComputerSystem -ErrorAction SilentlyContinue -Credential $cred | Select Username, PSComputerName
# If no User Information - continue
if (!($UserInfo.Username))
{
continue
}
else
{
$Username = $UserInfo.Username
$Computername = $UserInfo.PSComputerName
$LastLogon = Get-QADUser $UserInfo.Username -ErrorAction SilentlyContinue | select LastLogon
# Insert data to database
$Query2 = "INSERT INTO UsersLastLogon (Username, Computername, LastLogon) VALUES (@Username, @Computername, @LastLogon)"
Invoke-SqliteQuery -DataSource $Database -Query $Query2 -SqlParameters @{
Username = "$Username"
Computername = "$Computername"
LastLogon = $LastLogon.LastLogon
}
}
}
# Check database
Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM UsersLastLogon"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment