[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [Parameter(Mandatory = $true)] [string]$Csv, [switch]$Recurse, [switch]$Hash, [switch]$Force ) $ErrorActionPreference = 'Stop' if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "Folder not found: $Path" } $root = (Resolve-Path -LiteralPath $Path).Path $csvPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Csv) if ((Test-Path -LiteralPath $csvPath) -and (-not $Force)) { throw "CSV already exists: $csvPath. Add -Force to overwrite." } if ($Recurse) { $items = @(Get-ChildItem -LiteralPath $root -File -Recurse -ErrorAction SilentlyContinue) } else { $items = @(Get-ChildItem -LiteralPath $root -File -ErrorAction SilentlyContinue) } $items = @($items | Where-Object { $_.FullName -ne $csvPath }) $rows = foreach ($file in $items) { $relative = $file.FullName.Substring($root.Length).TrimStart([char[]]@('\', '/')) $row = [ordered]@{ RelativePath = $relative Name = $file.Name Extension = $file.Extension SizeBytes = $file.Length LastWriteTime = $file.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss') Attributes = $file.Attributes.ToString() } if ($Hash) { $row['SHA256'] = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash } [pscustomobject]$row } $rows = @($rows) if ($rows.Count -eq 0) { Write-Host 'No files found.' exit 0 } $rows | Export-Csv -LiteralPath $csvPath -NoTypeInformation -Encoding UTF8 Write-Host "Rows: $($rows.Count)" Write-Host "CSV saved: $csvPath"