diff --git a/4-m365-admin-scripts/README.md b/4-m365-admin-scripts/README.md new file mode 100644 index 0000000..74d56e1 --- /dev/null +++ b/4-m365-admin-scripts/README.md @@ -0,0 +1,263 @@ +# M365 Admin Scripts + +## Áttekintés / Overview + +PowerShell scriptek Microsoft 365 adminisztrációhoz Graph API használatával. + +PowerShell scripts for Microsoft 365 administration using Graph API. + +## Előfeltételek / Prerequisites + +### PowerShell Modulok / PowerShell Modules + +```powershell +# Microsoft Graph modulok telepítése / Install Microsoft Graph modules +Install-Module Microsoft.Graph -Scope CurrentUser + +# Vagy csak a szükséges modulok / Or just required modules +Install-Module Microsoft.Graph.Users -Scope CurrentUser +Install-Module Microsoft.Graph.Groups -Scope CurrentUser +Install-Module Microsoft.Graph.Identity.DirectoryManagement -Scope CurrentUser +Install-Module Microsoft.Graph.Reports -Scope CurrentUser +``` + +### Jogosultságok / Permissions + +Az alábbi Graph API jogosultságok szükségesek: +- `User.Read.All` - Felhasználók olvasása +- `Group.Read.All` - Csoportok olvasása +- `Directory.Read.All` - Könyvtár olvasása +- `Organization.Read.All` - Szervezet információk +- `AuditLog.Read.All` - Audit logok (riportokhoz) + +## Scriptek / Scripts + +### Kapcsolat / Connection + +#### Connect-M365.ps1 +Kapcsolódás Microsoft 365-höz Graph API-val. + +```powershell +# Kapcsolat modul importálása / Import connection module +. .\common\Connect-M365.ps1 + +# Kapcsolódás / Connect +Connect-M365Services -TenantId "your-tenant-id" + +# Kapcsolat ellenőrzése / Test connection +Test-M365Connection + +# Kapcsolat bontása / Disconnect +Disconnect-M365Services +``` + +### Felhasználó Kezelés / User Management + +#### Get-M365Users.ps1 +Felhasználók listázása részletes információkkal. + +```powershell +# Összes felhasználó / All users +.\users\Get-M365Users.ps1 + +# Szűrés névre / Filter by name +.\users\Get-M365Users.ps1 -Filter "startswith(displayName,'John')" + +# Export CSV-be / Export to CSV +.\users\Get-M365Users.ps1 -ExportPath "C:\temp\users.csv" +``` + +**Kimeneti adatok / Output data:** +- Megjelenítési név / Display name +- UPN (felhasználónév) +- Email cím +- Munkakör / Job title +- Részleg / Department +- Iroda helyszín / Office location +- Mobiltelefon / Mobile phone +- Fiók állapot / Account status +- Létrehozás dátuma / Creation date +- Utolsó bejelentkezés / Last sign-in + +### Csoport Kezelés / Group Management + +#### Get-M365Groups.ps1 +Csoportok listázása tagokkal. + +```powershell +# Összes csoport / All groups +.\groups\Get-M365Groups.ps1 + +# Csoport keresése névvel / Search by name +.\groups\Get-M365Groups.ps1 -GroupName "Sales" + +# Tagokkal együtt / Include members +.\groups\Get-M365Groups.ps1 -GroupName "IT" -IncludeMembers +``` + +**Információk / Information:** +- Csoport név / Group name +- Leírás / Description +- Csoport típus / Group type (M365, Security, Distribution) +- Email cím +- Tagok száma / Member count +- Tagok listája / Member list (ha kérjük) + +### Licenc Kezelés / License Management + +#### Get-M365Licenses.ps1 +Licenc használat riport. + +```powershell +# Licenc áttekintés / License overview +.\licenses\Get-M365Licenses.ps1 + +# Export CSV-be / Export to CSV +.\licenses\Get-M365Licenses.ps1 -ExportPath "C:\temp\licenses.csv" +``` + +**Riport tartalom / Report content:** +- Termék név / Product name +- Összes licenc / Total licenses +- Kiosztott licencek / Assigned licenses +- Elérhető licencek / Available licenses +- Kihasználtság % / Usage percentage +- Állapot / Status +- Figyelmeztetés alacsony készletnél / Warning for low availability + +### Riportok / Reports + +#### Get-M365InactiveUsers.ps1 +Inaktív felhasználók riport. + +```powershell +# 90 napja inaktív felhasználók / Users inactive for 90 days +.\reports\Get-M365InactiveUsers.ps1 + +# 30 napja inaktív / Inactive for 30 days +.\reports\Get-M365InactiveUsers.ps1 -DaysInactive 30 + +# Export / Export +.\reports\Get-M365InactiveUsers.ps1 -DaysInactive 90 -ExportPath "C:\temp\inactive.csv" +``` + +**Statisztikák / Statistics:** +- Inaktív aktív fiókok / Inactive enabled accounts +- Letiltott fiókok / Disabled accounts +- Soha nem bejelentkezett / Never signed in +- Ajánlások / Recommendations + +## Könyvtárstruktúra / Directory Structure + +``` +4-m365-admin-scripts/ +├── README.md # Ez a dokumentum / This document +├── common/ +│ └── Connect-M365.ps1 # Kapcsolat modul / Connection module +├── users/ +│ └── Get-M365Users.ps1 # Felhasználók lekérdezése / Get users +├── groups/ +│ └── Get-M365Groups.ps1 # Csoportok lekérdezése / Get groups +├── licenses/ +│ └── Get-M365Licenses.ps1 # Licencek lekérdezése / Get licenses +└── reports/ + └── Get-M365InactiveUsers.ps1 # Inaktív felhasználók / Inactive users +``` + +## Használati Példák / Usage Examples + +### Napi Ellenőrzés / Daily Check + +```powershell +# 1. Kapcsolódás / Connect +. .\common\Connect-M365.ps1 +Connect-M365Services + +# 2. Licenc helyzet / License status +.\licenses\Get-M365Licenses.ps1 + +# 3. Új felhasználók / New users (last 7 days) +.\users\Get-M365Users.ps1 -Filter "createdDateTime ge $((Get-Date).AddDays(-7).ToString('yyyy-MM-dd'))" + +# 4. Kapcsolat bontása / Disconnect +Disconnect-M365Services +``` + +### Havi Riport / Monthly Report + +```powershell +# Kapcsolódás / Connect +Connect-M365Services + +# Export könyvtár létrehozása / Create export directory +$exportDir = "C:\M365Reports\$(Get-Date -Format 'yyyy-MM')" +New-Item -Path $exportDir -ItemType Directory -Force + +# Riportok generálása / Generate reports +.\users\Get-M365Users.ps1 -ExportPath "$exportDir\users.csv" +.\groups\Get-M365Groups.ps1 -ExportPath "$exportDir\groups.csv" +.\licenses\Get-M365Licenses.ps1 -ExportPath "$exportDir\licenses.csv" +.\reports\Get-M365InactiveUsers.ps1 -DaysInactive 90 -ExportPath "$exportDir\inactive.csv" + +Write-Host "Riportok mentve: $exportDir" -ForegroundColor Green +``` + +### Licenc Auditálás / License Audit + +```powershell +# 1. Licenc áttekintés / License overview +$licenses = .\licenses\Get-M365Licenses.ps1 + +# 2. Alacsony készlet figyelmeztetés / Low availability warning +$lowStock = $licenses | Where-Object { $_.AvailableLicenses -lt 5 -and $_.TotalLicenses -gt 0 } +if ($lowStock) { + $lowStock | Format-Table ProductName, AvailableLicenses + Write-Warning "Figyelem: Alacsony licenc készlet! / Warning: Low license stock!" +} + +# 3. Kihasználatlan felhasználók / Unused users +$inactiveUsers = .\reports\Get-M365InactiveUsers.ps1 -DaysInactive 90 +Write-Host "$($inactiveUsers.Count) felhasználó inaktív 90 napja" +``` + +## Biztonság / Security + +### Kapcsolat Kezelés / Connection Management +- Graph API OAuth2 hitelesítés / OAuth2 authentication +- Munkamenet kezelés / Session management +- Automatikus token frissítés / Automatic token refresh + +### Audit és Napló / Audit and Logging +- Minden művelet naplózva a Microsoft Audit Log-ban +- Sign-in activity tracking +- License change tracking + +### Best Practices +- Mindig használj minimális jogosultságokat / Always use least privilege +- Kapcsolódj csak amikor szükséges / Connect only when needed +- Kapcsolat bontása használat után / Disconnect after use +- Érzékeny adatok exportálása biztonságosan / Export sensitive data securely + +## Hibaelhárítás / Troubleshooting + +### Kapcsolódási Hiba / Connection Error +```powershell +# Module ellenőrzés / Check module +Get-Module Microsoft.Graph -ListAvailable + +# Újratelepítés / Reinstall +Install-Module Microsoft.Graph -Force -AllowClobber +``` + +### Jogosultság Hiba / Permission Error +```powershell +# Jelenlegi jogosultságok / Current permissions +(Get-MgContext).Scopes + +# Újracsatlakozás több jogosultsággal / Reconnect with more scopes +Connect-M365Services -Scopes @("User.Read.All", "Group.Read.All", "Directory.Read.All") +``` + +## Licenc / License + +MIT License diff --git a/4-m365-admin-scripts/common/Connect-M365.ps1 b/4-m365-admin-scripts/common/Connect-M365.ps1 new file mode 100644 index 0000000..ccc11fa --- /dev/null +++ b/4-m365-admin-scripts/common/Connect-M365.ps1 @@ -0,0 +1,117 @@ +<# +.SYNOPSIS + Microsoft 365 kapcsolat modul / Microsoft 365 connection module + +.DESCRIPTION + Kapcsolódás Microsoft 365 szolgáltatásokhoz Graph API-val. + Connects to Microsoft 365 services using Graph API. + +.PARAMETER TenantId + Tenant azonosító / Tenant ID + +.PARAMETER Scopes + Szükséges jogosultságok / Required scopes + +.EXAMPLE + . .\Connect-M365.ps1 + Connect-M365Services -TenantId "your-tenant-id" + +.NOTES + Requires: Microsoft.Graph PowerShell SDK + Install-Module Microsoft.Graph -Scope CurrentUser +#> + +function Connect-M365Services { + [CmdletBinding()] + param( + [Parameter(Mandatory = $false)] + [string]$TenantId, + + [Parameter(Mandatory = $false)] + [string[]]$Scopes = @( + "User.Read.All", + "Group.Read.All", + "Directory.Read.All", + "Organization.Read.All" + ) + ) + + begin { + Write-Host "M365 kapcsolódás indítása / Starting M365 connection..." -ForegroundColor Cyan + } + + process { + try { + # Ellenőrizzük hogy telepítve van-e a Microsoft.Graph modul + # Check if Microsoft.Graph module is installed + if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) { + throw "Microsoft.Graph modul nincs telepítve / Microsoft.Graph module not installed. Run: Install-Module Microsoft.Graph" + } + + # Kapcsolódás / Connect + $connectParams = @{ + Scopes = $Scopes + } + + if ($TenantId) { + $connectParams.TenantId = $TenantId + } + + Connect-MgGraph @connectParams -NoWelcome + + # Kapcsolat ellenőrzése / Verify connection + $context = Get-MgContext + if ($context) { + Write-Host "Sikeres kapcsolódás / Successfully connected" -ForegroundColor Green + Write-Host " Tenant ID: $($context.TenantId)" -ForegroundColor Gray + Write-Host " Account: $($context.Account)" -ForegroundColor Gray + Write-Host " Scopes: $($context.Scopes -join ', ')" -ForegroundColor Gray + return $true + } + else { + throw "Kapcsolódás sikertelen / Connection failed" + } + } + catch { + Write-Error "Hiba a kapcsolódás során / Error during connection: $_" + return $false + } + } +} + +function Disconnect-M365Services { + [CmdletBinding()] + param() + + try { + Disconnect-MgGraph -ErrorAction SilentlyContinue + Write-Host "Kapcsolat bontva / Disconnected" -ForegroundColor Green + } + catch { + Write-Warning "Hiba a kapcsolat bontása során / Error during disconnect: $_" + } +} + +function Test-M365Connection { + [CmdletBinding()] + param() + + try { + $context = Get-MgContext -ErrorAction Stop + if ($context) { + Write-Host "Kapcsolat aktív / Connection active" -ForegroundColor Green + return $true + } + else { + Write-Host "Nincs aktív kapcsolat / No active connection" -ForegroundColor Yellow + return $false + } + } + catch { + Write-Host "Nincs aktív kapcsolat / No active connection" -ForegroundColor Yellow + return $false + } +} + +# Export functions +Export-ModuleMember -Function Connect-M365Services, Disconnect-M365Services, Test-M365Connection diff --git a/4-m365-admin-scripts/groups/Get-M365Groups.ps1 b/4-m365-admin-scripts/groups/Get-M365Groups.ps1 new file mode 100644 index 0000000..e85063c --- /dev/null +++ b/4-m365-admin-scripts/groups/Get-M365Groups.ps1 @@ -0,0 +1,126 @@ +<# +.SYNOPSIS + M365 csoportok lekérdezése / Get M365 groups + +.DESCRIPTION + Microsoft 365 csoportok listázása tagokkal. + Lists Microsoft 365 groups with members. + +.PARAMETER GroupName + Csoport név szűrő / Group name filter + +.PARAMETER IncludeMembers + Tagok megjelenítése / Include members + +.EXAMPLE + .\Get-M365Groups.ps1 + +.EXAMPLE + .\Get-M365Groups.ps1 -GroupName "Sales" -IncludeMembers + +.NOTES + Requires: Microsoft.Graph.Groups module +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string]$GroupName, + + [Parameter(Mandatory = $false)] + [switch]$IncludeMembers +) + +begin { + # Import kapcsolat modul / Import connection module + $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path + . (Join-Path (Split-Path $scriptPath) "common\Connect-M365.ps1") + + Write-Host "M365 csoportok lekérdezése / Getting M365 groups..." -ForegroundColor Cyan +} + +process { + try { + # Kapcsolat ellenőrzése / Check connection + if (-not (Test-M365Connection)) { + Connect-M365Services -Scopes @("Group.Read.All", "GroupMember.Read.All") | Out-Null + } + + # Csoportok lekérdezése / Get groups + $getGroupParams = @{ + All = $true + Property = @( + 'Id', + 'DisplayName', + 'Description', + 'GroupTypes', + 'Mail', + 'MailEnabled', + 'SecurityEnabled', + 'CreatedDateTime' + ) + } + + if ($GroupName) { + $getGroupParams.Filter = "startswith(displayName,'$GroupName')" + } + + $groups = Get-MgGroup @getGroupParams + + Write-Host "Találatok: $($groups.Count) csoport / Found: $($groups.Count) groups" -ForegroundColor Green + + # Eredmények feldolgozása / Process results + $results = foreach ($group in $groups) { + $memberCount = 0 + $members = @() + + if ($IncludeMembers) { + $groupMembers = Get-MgGroupMember -GroupId $group.Id -All + $memberCount = $groupMembers.Count + $members = $groupMembers | ForEach-Object { + Get-MgUser -UserId $_.Id -Property DisplayName, UserPrincipalName -ErrorAction SilentlyContinue | + Select-Object DisplayName, UserPrincipalName + } + } + + [PSCustomObject]@{ + DisplayName = $group.DisplayName + Description = $group.Description + Type = if ($group.GroupTypes -contains "Unified") { "Microsoft 365" } else { "Security/Distribution" } + Mail = $group.Mail + MailEnabled = $group.MailEnabled + SecurityEnabled = $group.SecurityEnabled + MemberCount = $memberCount + Members = if ($members) { ($members.DisplayName -join '; ') } else { "" } + Created = $group.CreatedDateTime + Id = $group.Id + } + } + + # Megjelenítés / Display + if ($IncludeMembers) { + $results | Format-List + } + else { + $results | Format-Table DisplayName, Type, Mail, SecurityEnabled, MemberCount, Created -AutoSize + } + + # Statisztikák / Statistics + $m365Groups = ($results | Where-Object { $_.Type -eq "Microsoft 365" }).Count + $securityGroups = ($results | Where-Object { $_.SecurityEnabled }).Count + + Write-Host "`nStatisztikák / Statistics:" -ForegroundColor Cyan + Write-Host " Microsoft 365 csoportok / Microsoft 365 groups: $m365Groups" -ForegroundColor Green + Write-Host " Biztonsági csoportok / Security groups: $securityGroups" -ForegroundColor Green + + return $results + } + catch { + Write-Error "Hiba a csoportok lekérdezése során / Error getting groups: $_" + throw + } +} + +end { + Write-Host "Kész / Done!" -ForegroundColor Green +} diff --git a/4-m365-admin-scripts/licenses/Get-M365Licenses.ps1 b/4-m365-admin-scripts/licenses/Get-M365Licenses.ps1 new file mode 100644 index 0000000..ad8c4e8 --- /dev/null +++ b/4-m365-admin-scripts/licenses/Get-M365Licenses.ps1 @@ -0,0 +1,133 @@ +<# +.SYNOPSIS + M365 licencek lekérdezése / Get M365 licenses + +.DESCRIPTION + Microsoft 365 licenc használat riport. + Microsoft 365 license usage report. + +.PARAMETER ExportPath + Export CSV útvonala / CSV export path + +.EXAMPLE + .\Get-M365Licenses.ps1 + +.EXAMPLE + .\Get-M365Licenses.ps1 -ExportPath "C:\temp\licenses.csv" + +.NOTES + Requires: Microsoft.Graph.Identity.DirectoryManagement module +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string]$ExportPath +) + +begin { + # Import kapcsolat modul / Import connection module + $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path + . (Join-Path (Split-Path $scriptPath) "common\Connect-M365.ps1") + + Write-Host "M365 licencek lekérdezése / Getting M365 licenses..." -ForegroundColor Cyan +} + +process { + try { + # Kapcsolat ellenőrzése / Check connection + if (-not (Test-M365Connection)) { + Connect-M365Services -Scopes @("Organization.Read.All", "Directory.Read.All") | Out-Null + } + + # Előfizetett SKU-k lekérdezése / Get subscribed SKUs + $skus = Get-MgSubscribedSku -All + + Write-Host "Találatok: $($skus.Count) licenc típus / Found: $($skus.Count) license types" -ForegroundColor Green + + # Licenc nevek map / License name mapping + $licenseNames = @{ + "ENTERPRISEPACK" = "Office 365 E3" + "ENTERPRISEPREMIUM" = "Office 365 E5" + "SPE_E3" = "Microsoft 365 E3" + "SPE_E5" = "Microsoft 365 E5" + "STANDARDPACK" = "Office 365 E1" + "EXCHANGESTANDARD" = "Exchange Online Plan 1" + "EXCHANGEENTERPRISE" = "Exchange Online Plan 2" + "POWER_BI_PRO" = "Power BI Pro" + "PROJECTPROFESSIONAL" = "Project Plan 3" + "VISIOCLIENT" = "Visio Plan 2" + } + + # Eredmények formázása / Format results + $results = foreach ($sku in $skus) { + $skuPart = $sku.SkuPartNumber + $friendlyName = if ($licenseNames.ContainsKey($skuPart)) { + $licenseNames[$skuPart] + } else { + $skuPart + } + + $enabled = $sku.PrepaidUnits.Enabled + $consumed = $sku.ConsumedUnits + $available = $enabled - $consumed + $usagePercent = if ($enabled -gt 0) { + [math]::Round(($consumed / $enabled) * 100, 2) + } else { 0 } + + [PSCustomObject]@{ + ProductName = $friendlyName + SkuId = $sku.SkuId + SkuPartNumber = $skuPart + TotalLicenses = $enabled + AssignedLicenses = $consumed + AvailableLicenses = $available + UsagePercent = $usagePercent + Status = $sku.CapabilityStatus + } + } + + # Megjelenítés / Display + $results | Sort-Object AssignedLicenses -Descending | + Format-Table ProductName, TotalLicenses, AssignedLicenses, AvailableLicenses, UsagePercent, Status -AutoSize + + # Export ha kértük / Export if requested + if ($ExportPath) { + $results | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + Write-Host "Exportálva: $ExportPath" -ForegroundColor Green + } + + # Statisztikák / Statistics + $totalLicenses = ($results | Measure-Object -Property TotalLicenses -Sum).Sum + $assignedLicenses = ($results | Measure-Object -Property AssignedLicenses -Sum).Sum + $availableLicenses = $totalLicenses - $assignedLicenses + $overallUsage = if ($totalLicenses -gt 0) { + [math]::Round(($assignedLicenses / $totalLicenses) * 100, 2) + } else { 0 } + + Write-Host "`nÖsszesített statisztikák / Overall statistics:" -ForegroundColor Cyan + Write-Host " Összes licenc / Total licenses: $totalLicenses" -ForegroundColor White + Write-Host " Kiosztott / Assigned: $assignedLicenses" -ForegroundColor Green + Write-Host " Elérhető / Available: $availableLicenses" -ForegroundColor Yellow + Write-Host " Kihasználtság / Usage: $overallUsage%" -ForegroundColor $(if ($overallUsage -gt 90) { "Red" } elseif ($overallUsage -gt 75) { "Yellow" } else { "Green" }) + + # Figyelmeztetések / Warnings + $lowAvailability = $results | Where-Object { $_.AvailableLicenses -lt 5 -and $_.TotalLicenses -gt 0 } + if ($lowAvailability) { + Write-Host "`nFigyelmeztetés / Warning: Alacsony licenc készlet / Low license availability:" -ForegroundColor Yellow + $lowAvailability | ForEach-Object { + Write-Host " $($_.ProductName): $($_.AvailableLicenses) elérhető" -ForegroundColor Yellow + } + } + + return $results + } + catch { + Write-Error "Hiba a licencek lekérdezése során / Error getting licenses: $_" + throw + } +} + +end { + Write-Host "Kész / Done!" -ForegroundColor Green +} diff --git a/4-m365-admin-scripts/reports/Get-M365InactiveUsers.ps1 b/4-m365-admin-scripts/reports/Get-M365InactiveUsers.ps1 new file mode 100644 index 0000000..829818f --- /dev/null +++ b/4-m365-admin-scripts/reports/Get-M365InactiveUsers.ps1 @@ -0,0 +1,137 @@ +<# +.SYNOPSIS + Inaktív M365 felhasználók riportja / M365 inactive users report + +.DESCRIPTION + Felhasználók akik X napja nem jelentkeztek be. + Users who haven't signed in for X days. + +.PARAMETER DaysInactive + Inaktivitás napokban / Days of inactivity (default: 90) + +.PARAMETER ExportPath + Export CSV útvonala / CSV export path + +.EXAMPLE + .\Get-M365InactiveUsers.ps1 -DaysInactive 30 + +.EXAMPLE + .\Get-M365InactiveUsers.ps1 -DaysInactive 90 -ExportPath "C:\temp\inactive.csv" + +.NOTES + Requires: Microsoft.Graph.Users, Microsoft.Graph.Reports modules +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [int]$DaysInactive = 90, + + [Parameter(Mandatory = $false)] + [string]$ExportPath +) + +begin { + # Import kapcsolat modul / Import connection module + $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path + . (Join-Path (Split-Path $scriptPath) "common\Connect-M365.ps1") + + Write-Host "Inaktív felhasználók keresése ($DaysInactive nap) / Finding inactive users ($DaysInactive days)..." -ForegroundColor Cyan +} + +process { + try { + # Kapcsolat ellenőrzése / Check connection + if (-not (Test-M365Connection)) { + Connect-M365Services -Scopes @("User.Read.All", "AuditLog.Read.All") | Out-Null + } + + # Küszöb dátum / Threshold date + $thresholdDate = (Get-Date).AddDays(-$DaysInactive) + + Write-Host "Küszöb dátum / Threshold date: $($thresholdDate.ToString('yyyy-MM-dd'))" -ForegroundColor Gray + + # Felhasználók lekérdezése / Get users + $users = Get-MgUser -All -Property ` + Id, DisplayName, UserPrincipalName, Mail, Department, JobTitle, ` + AccountEnabled, CreatedDateTime, SignInActivity + + Write-Host "Összesen $($users.Count) felhasználó ellenőrzése / Checking $($users.Count) users..." -ForegroundColor Gray + + # Inaktív felhasználók szűrése / Filter inactive users + $inactiveUsers = $users | Where-Object { + $lastSignIn = $_.SignInActivity.LastSignInDateTime + + # Ha nincs bejelentkezési adat, vagy régebbi mint a küszöb + # If no sign-in data or older than threshold + (-not $lastSignIn) -or ($lastSignIn -lt $thresholdDate) + } + + Write-Host "Találatok: $($inactiveUsers.Count) inaktív felhasználó / Found: $($inactiveUsers.Count) inactive users" -ForegroundColor Yellow + + # Eredmények formázása / Format results + $results = $inactiveUsers | ForEach-Object { + $daysSinceSignIn = if ($_.SignInActivity.LastSignInDateTime) { + ((Get-Date) - $_.SignInActivity.LastSignInDateTime).Days + } else { + "Nincs adat / No data" + } + + [PSCustomObject]@{ + DisplayName = $_.DisplayName + UserPrincipalName = $_.UserPrincipalName + Mail = $_.Mail + Department = $_.Department + JobTitle = $_.JobTitle + AccountEnabled = $_.AccountEnabled + LastSignIn = if ($_.SignInActivity.LastSignInDateTime) { + $_.SignInActivity.LastSignInDateTime.ToString('yyyy-MM-dd HH:mm') + } else { + "Nincs / Never" + } + DaysSinceSignIn = $daysSinceSignIn + Created = $_.CreatedDateTime.ToString('yyyy-MM-dd') + Id = $_.Id + } + } + + # Megjelenítés / Display + $results | Sort-Object DisplayName | + Format-Table DisplayName, UserPrincipalName, Department, AccountEnabled, LastSignIn, DaysSinceSignIn -AutoSize + + # Export ha kértük / Export if requested + if ($ExportPath) { + $results | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + Write-Host "Exportálva: $ExportPath" -ForegroundColor Green + } + + # Statisztikák / Statistics + $enabledInactive = ($results | Where-Object { $_.AccountEnabled }).Count + $disabledInactive = $results.Count - $enabledInactive + $neverSignedIn = ($results | Where-Object { $_.LastSignIn -eq "Nincs / Never" }).Count + + Write-Host "`nStatisztikák / Statistics:" -ForegroundColor Cyan + Write-Host " Aktív fiókok (inaktív) / Enabled accounts (inactive): $enabledInactive" -ForegroundColor Yellow + Write-Host " Letiltott fiókok / Disabled accounts: $disabledInactive" -ForegroundColor Gray + Write-Host " Soha nem jelentkezett be / Never signed in: $neverSignedIn" -ForegroundColor Red + + # Ajánlások / Recommendations + if ($enabledInactive -gt 0) { + Write-Host "`nAjánlás / Recommendation:" -ForegroundColor Cyan + Write-Host " $enabledInactive aktív fiók inaktív $DaysInactive napja." -ForegroundColor Yellow + Write-Host " Fontolja meg a fiókok felülvizsgálatát vagy letiltását." -ForegroundColor Yellow + Write-Host " $enabledInactive enabled accounts inactive for $DaysInactive days." -ForegroundColor Yellow + Write-Host " Consider reviewing or disabling these accounts." -ForegroundColor Yellow + } + + return $results + } + catch { + Write-Error "Hiba az inaktív felhasználók lekérdezése során / Error getting inactive users: $_" + throw + } +} + +end { + Write-Host "Kész / Done!" -ForegroundColor Green +} diff --git a/4-m365-admin-scripts/users/Get-M365Users.ps1 b/4-m365-admin-scripts/users/Get-M365Users.ps1 new file mode 100644 index 0000000..3732483 --- /dev/null +++ b/4-m365-admin-scripts/users/Get-M365Users.ps1 @@ -0,0 +1,121 @@ +<# +.SYNOPSIS + M365 felhasználók lekérdezése / Get M365 users + +.DESCRIPTION + Microsoft 365 felhasználók listázása részletes információkkal. + Lists Microsoft 365 users with detailed information. + +.PARAMETER Filter + Szűrő kifejezés / Filter expression (OData) + +.PARAMETER ExportPath + Export CSV útvonala / CSV export path + +.EXAMPLE + .\Get-M365Users.ps1 + +.EXAMPLE + .\Get-M365Users.ps1 -Filter "startswith(displayName,'John')" + +.EXAMPLE + .\Get-M365Users.ps1 -ExportPath "C:\temp\users.csv" + +.NOTES + Requires: Microsoft.Graph.Users module +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string]$Filter, + + [Parameter(Mandatory = $false)] + [string]$ExportPath +) + +begin { + # Import kapcsolat modul / Import connection module + $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path + . (Join-Path (Split-Path $scriptPath) "common\Connect-M365.ps1") + + Write-Host "M365 felhasználók lekérdezése / Getting M365 users..." -ForegroundColor Cyan +} + +process { + try { + # Kapcsolat ellenőrzése / Check connection + if (-not (Test-M365Connection)) { + Write-Host "Kapcsolódás szükséges / Connection required..." -ForegroundColor Yellow + Connect-M365Services -Scopes @("User.Read.All") | Out-Null + } + + # Felhasználók lekérdezése / Get users + $getUserParams = @{ + All = $true + Property = @( + 'Id', + 'DisplayName', + 'UserPrincipalName', + 'Mail', + 'JobTitle', + 'Department', + 'OfficeLocation', + 'MobilePhone', + 'AccountEnabled', + 'CreatedDateTime', + 'SignInActivity' + ) + } + + if ($Filter) { + $getUserParams.Filter = $Filter + } + + Write-Host "Lekérdezés futtatása / Running query..." -ForegroundColor Gray + $users = Get-MgUser @getUserParams + + Write-Host "Találatok: $($users.Count) felhasználó / Found: $($users.Count) users" -ForegroundColor Green + + # Eredmények formázása / Format results + $results = $users | Select-Object ` + DisplayName, + UserPrincipalName, + Mail, + JobTitle, + Department, + OfficeLocation, + MobilePhone, + @{Name='Enabled'; Expression={$_.AccountEnabled}}, + @{Name='Created'; Expression={$_.CreatedDateTime}}, + @{Name='LastSignIn'; Expression={$_.SignInActivity.LastSignInDateTime}}, + Id + + # Megjelenítés / Display + $results | Format-Table -AutoSize + + # Export ha kértük / Export if requested + if ($ExportPath) { + $results | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + Write-Host "Exportálva: $ExportPath" -ForegroundColor Green + } + + # Statisztikák / Statistics + $enabledCount = ($users | Where-Object { $_.AccountEnabled }).Count + $disabledCount = $users.Count - $enabledCount + + Write-Host "`nStatisztikák / Statistics:" -ForegroundColor Cyan + Write-Host " Aktív felhasználók / Active users: $enabledCount" -ForegroundColor Green + Write-Host " Inaktív felhasználók / Inactive users: $disabledCount" -ForegroundColor Yellow + + return $results + } + catch { + Write-Error "Hiba a felhasználók lekérdezése során / Error getting users: $_" + throw + } +} + +end { + Write-Host "Kész / Done!" -ForegroundColor Green +}