function Get-AllDrives {
return Get-PSDrive -PSProvider FileSystem |
Where-Object { $_.Root -ne $null } |
Select-Object -ExpandProperty Root
}
function Enable-FileSystemAuditing {
auditpol /set /subcategory:"File System" /success:enable /failure:enable | Out-
Null
return $true
}
function Add-AuditRules {
param (
[Parameter(Mandatory=$true)]
[string[]]$Paths,
[Parameter(Mandatory=$true)]
[string[]]$Users
)
try {
Import-Module NTFSSecurity -ErrorAction SilentlyContinue
$auditUsers = $Users + @('SYSTEM', 'Everyone', 'Administrators')
foreach ($path in $Paths) {
if (Test-Path $path) {
foreach ($user in $auditUsers) {
try {
Add-NTFSAudit -Path $path -Account $user `
-AuditType FileSystemRights `
-AccessRight Read, Write, Delete, Modify, FullControl `
-Success `
-Failure `
-ErrorAction SilentlyContinue | Out-Null
}
catch {}
}
}
}
return $true
}
catch {
return $false
}
}
function Get-FileSystemEvents {
param (
[Parameter(Mandatory=$true)]
[string[]]$Paths,
[Parameter(Mandatory=$false)]
[int]$Hours = 24
)
try {
$outputDir = "C:\Temp\drive_audit_logs"
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}
$outputFile = Join-Path $outputDir "Audit_Disques_$(Get-Date -Format
'yyyyMMdd_HHmmss').csv"
$startTime = (Get-Date).AddHours(-$Hours)
$eventIds = @(4656, 4660, 4663, 4670, 4690)
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = $eventIds
StartTime = $startTime
} -ErrorAction SilentlyContinue
$results = $events | Where-Object {
$path = $_.Properties[6].Value
$Paths | Where-Object { $path -like "*$_*" }
} | ForEach-Object {
Get-EventDetails -Event $_
} | Where-Object { $null -ne $_ }
if ($results.Count -gt 0) {
$results | Export-Csv -Path $outputFile -NoTypeInformation -Encoding
UTF8
}
return $results
}
catch {
return @()
}
}
function Main {
$isAdmin = ([Security.Principal.WindowsPrincipal]
[Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.Wi
ndowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
return
}
Enable-FileSystemAuditing
$drives = Get-AllDrives
$usersToMonitor = @("Utilisateur1", "Utilisateur2")
$hoursToMonitor = 48
Add-AuditRules -Paths $drives -Users $usersToMonitor
$events = Get-FileSystemEvents -Paths $drives -Hours $hoursToMonitor
}
Main