Skip to main content

Extract AD pc non connecté

$DaysInactive = 60  

$InactiveDate = (Get-Date).AddDays(-$DaysInactive)
$ExportFile = "C:\temp\InactiveComputers.csv"


$Computers = Get-ADComputer -Filter * -Properties LastLogonDate, Description


$InactiveComputers = $Computers | Where-Object { $_.LastLogonDate -lt $InactiveDate }

$InactiveComputerDataWithUser = foreach ($computer in $InactiveComputers) {
      $computerName = $computer.Name
      $description = $computer.Description

      $lastLogon = $computer.LastLogonDate
      $lastLogonUser = Get-ADUser -Filter "SamAccountName -eq '$($computer.SamAccountName)'" -Property SamAccountName |
          Select-Object -ExpandProperty SamAccountName

      [PSCustomObject]@{
          ComputerName = $computerName
          Description = $description
          LastLogonDate = $lastLogon
          User = $lastLogonUser
      }
}

$ExportDescription = "List of inactive computers that have not logged on in the last $DaysInactive days."
$InactiveComputerDataWithUser | Export-Csv -Path $ExportFile -NoTypeInformation -Append
Add-Content -Path $ExportFile -Value "`nDescription: $ExportDescription"