Skip to content

Instantly share code, notes, and snippets.

@MaraScott
Created May 28, 2024 21:04
Show Gist options
  • Save MaraScott/94189c90c5b35500006e570e0654f658 to your computer and use it in GitHub Desktop.
Save MaraScott/94189c90c5b35500006e570e0654f658 to your computer and use it in GitHub Desktop.
param(
[string]$DirectoryPath = ".",
[string]$CsvFilePath = ".\directory_list.csv"
)
# Function to check if a directory is already listed in the CSV
function Read-DirectoryRow {
param(
$DataTable,
[string]$DirectoryName
)
foreach ($row in $DataTable) {
if ($row.Name -eq $DirectoryName) {
return $row
}
}
return $null
}
# Function to create the CSV schema
function New-CsvSchema {
$DataTable = @()
$row = [PSCustomObject]@{
Name = ""
Count = ""
Date = ""
}
$DataTable += $row
$DataTable | Export-Csv -Path $CsvFilePath -NoTypeInformation
}
# Initialize DataTable
$DataTable = @()
# Load existing CSV file or create a new DataTable
if (-not (Test-Path $CsvFilePath)) {
New-CsvSchema
}
$csvData = Import-Csv $CsvFilePath
if ($csvData.Count -gt 0) {
foreach ($csvRow in $csvData) {
$row = [PSCustomObject]@{
Name = $csvRow.Name
Count = [int]$csvRow.Count
Date = $csvRow.Date
}
$DataTable += $row
}
}
# Get the list of directories
$Directories = Get-ChildItem -Path $DirectoryPath -Directory
foreach ($Directory in $Directories) {
$row = Read-DirectoryRow -DataTable $DataTable -DirectoryName $Directory.Name
if ($null -eq $row) {
$row = [PSCustomObject]@{
Name = $Directory.Name
Count = 1
Date = (Get-Date -Format "yyyy-MM-dd")
}
$DataTable += $row
Write-Output "New row added:"
Write-Output $row
} else {
$row.Count += 1
Write-Output "Existing row updated:"
Write-Output $row
}
$DirectoryPath = $Directory.FullName
Remove-Item -Path "$DirectoryPath" -Recurse -Force
}
# Save the DataTable back to the CSV file
$DataTable | Export-Csv -Path $CsvFilePath -NoTypeInformation
Write-Output "Directory listing updated successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment