How to Create a FolderName Variable in PowerShell that equals an Exact Name

52 views Asked by At

I am working on a script that basically looks for a folder name and then recurses through the folder structure finding files with a specific extension and then delete those files older than X amount of days, then output the results into a CSV file.

# *IMPORTANT* DOUBLE CHECK
$fileType = '*.dwg'
$foldername = "Site Plans"

# *IMPORTANT* DOUBLE CHECK - Get the current date and calculate the date -XX days ago
$currentDate = Get-Date
$cutOffDate = $currentDate.AddDays(-1)

### START SCRIPT ### 
#$path = "C:\Users\zbarchuk\desktop\Site Plans - Copy"
$path = Get-ChildItem -Path C:\ | Where-Object {$_.Name -eq $foldername}

# Get Top Folder Name from path
#$pathTopFolder = ($path).split("\")[-1]

# $PSScriptRoot is the current path to the script ****
$GetDate = Get-Date -Format "MM-dd-yyyy_HH_mm_ss"

# File Stats
$log = [System.Collections.ArrayList]@("FileName, FilePath, FileSize")
$TotalSize = 0

# Get all files with the .pdf extension that are older than 45 days in all directories and subdirectories
$filesToDelete = Get-ChildItem -Path $path -Recurse -Filter $fileType | Where-Object { $_.LastWriteTime -lt $cutOffDate }

# Get File Item Count
$count = 1
$fileCount = @($filesToDelete).Count

# Delete each file
$OutputLog = @()
foreach ($file in $filesToDelete) {
    
    #Get Item Size and add to file array
    $size=[math]::Round((Get-Item -LiteralPath $file.FullName).length/1MB,2)

    
    Write-Progress -Activity $count"/"$fileCount
    #Write-Host -Activity "Deleting " $file.FullName

    #Calc total size of deleted files
    $TotalSize = ($TotalSize + $size)
    
    #Remove-Item $file.FullName -Force
    $count = $count+1

    $OutputLog+=@([PSCustomObject]@{
        FileName = $file
        FilePath = Split-Path -Parent ($file.FullName)
        FileSize = "$size" + " MB"
    })
    
}

$OutputLog+=@([PSCustomObject]@{
        FileName = "Total PDF File Cleanup Size"
        FilePath = "Total Items=$fileCount"
        FileSize = "$TotalSize MB"
    })

$OutputLog | Export-CSv -Path C:\users\zbarchuk\desktop\CleanupOutputLog.csv

The issue I am running into and can't seem to figure out is the $path Get-ChildItem code is grabbing all folders with a similar name to the one I am looking for. I have tried various iterations using -Unique -Eq -Match but nothing seems to set it to only look for that specific folder name. Any help would be greatly appreciated!

1

There are 1 answers

2
lit On

This code takes into account that there could be multiple Site Plans directories. It also omits the summary totals in favor of doing it from the log file after completion.

The Remove-Item command is used, but it has -WhatIf which will cause it to only report what it would do. This allows you to safely run the script many times without deleting any files.

# *IMPORTANT* DOUBLE CHECK
$fileType = '.dwg'
$foldername = "Site Plans"

# *IMPORTANT* DOUBLE CHECK - Get the current date and calculate the date -XX days ago
$currentDate = Get-Date
$cutOffDate = $currentDate.AddDays(-1)

### START SCRIPT ### 
$paths = Get-ChildItem -Recurse -Directory -Path 'C:\' -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq $foldername}
$filestodelete = @()

foreach ($path in $paths) {
    # Get all files with the $filetype extension that are older than 45 days in all directories and subdirectories
    $filesToDelete += Get-ChildItem -File -Path $path -Recurse |
        Where-Object { ($_.Extension -eq $filetype) -and ($_.LastWriteTime -lt $cutOffDate) }
}

# Get File Item Count
$count = 1
$fileCount = $filesToDelete.Count

# Delete each file
$OutputLog = @()
foreach ($file in $filesToDelete) {
    Write-Progress -Activity "$count/$fileCount"
    Write-Information "Deleting $($file.FullName)"

    # Remove the file
    Remove-Item $file.FullName -Force -Whatif
    $count++

    $OutputLog += [PSCustomObject]@{
        FileName = $file.Name
        FilePath = $file.DirectoryName
        FileSize = $file.Length
    }
}

$LogFileFullName = Join-Path -Path $Env:USERPROFILE -ChildPath 'CleanupOutputLog.csv'
$OutputLog | Export-Csv -Path $LogFileFullName

After producing the log file, generate the count and size with:

Import-Csv -Path .\CleanupOutputLog.csv | Measure-Object -Sum FileSize

or

(Import-Csv -Path .\CleanupOutputLog.csv | Measure-Object -Sum FileSize).Sum / 1MB