Agents/controller/Exchange-User-Export.ps1

85 lines
3.0 KiB
PowerShell

# Definieren Sie den Pfad zur Ergebnisdatei
$timestamp = (Get-Date).ToString("yyyyMMdd_HHmmss")
$outputFile = "C:\Scripte\MailboxLastLogins_$timestamp.csv"
# Definieren Sie den API-Endpoint
$apiUrl = "http://api.stines.de:8001/report"
# Your API key
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")
$headers.Add("access_token", "^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8")
$ipaddress = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -like "*Ethernet*" } | Select-Object -ExpandProperty IPAddress
# Fügen Sie das Exchange-Management-Snap-In hinzu
if (-not (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue)) {
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
}
# Ermitteln Sie alle Benutzerpostfächer
$mailboxes = Get-Mailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited
# Initialisieren Sie eine leere Liste für die Ergebnisse
$results = @()
# Zeitstempel für eine Stunde zuvor
$oneHourAgo = (Get-Date).AddHours(-1)
# Durchlaufen Sie alle Postfächer und sammeln Sie die letzten Login-Informationen
foreach ($mailbox in $mailboxes) {
# Überprüfen, ob das Konto deaktiviert ist
$exchangeUserAccountControl = $mailbox.ExchangeUserAccountControl
if ($exchangeUserAccountControl -eq "AccountDisabled") {
continue
}
# Filter für Admin- und Journalpostfächer
if ($mailbox.UserPrincipalName -eq "$" -or
$mailbox.UserPrincipalName -match "Journal" -or
$mailbox.UserPrincipalName -match "admin") {
continue
}
$mailboxStats = Get-MailboxStatistics -Identity $mailbox.UserPrincipalName
$lastLoginTime = $mailboxStats.LastLogonTime
# Prüfen, ob der letzte Login in der letzten Stunde war
if ($lastLoginTime -ge $oneHourAgo) {
$username = $mailbox.UserPrincipalName.Split('@')[0]
$result = [PSCustomObject]@{
Mailbox = $username
LastLogon = $lastLoginTime
}
$results += $result
# Daten für die API-Anfrage vorbereiten
$data = @{
username = $result.Mailbox
lastaccess = $result.LastLogon.ToString("yyyy-MM-dd HH:mm:ss")
ipaddress = $ipaddress
}
# POST-Anfrage an den API-Server senden
$jsonData = ($data | ConvertTo-Json -Depth 3 | Out-String).Trim()
$utf8Json = [System.Text.Encoding]::UTF8.GetBytes($jsonData)
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $utf8Json -ContentType "application/json; charset=utf-8" -Headers $headers
if ($response -eq "True") {
Write-Output "Successfully sent data for $($result.Mailbox)"
} else {
Write-Output "Failed to send data for $($result.Mailbox): $response"
}
}
}
# Ergebnisse in CSV exportieren
$results | Export-Csv -Path $outputFile -NoTypeInformation
# Ergebnisse anzeigen
$results | Format-Table -AutoSize