You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本需求:从路径提取标识并展示文件清理状态

Got it, let's solve this. The core idea is to first create a clear mapping between your target paths and their friendly display names (like "Jira - Logs"), then refactor your existing cleanup logic into a reusable function that outputs the required section headers in real-time as it processes each path.

Step 1: Define Path-to-Identifier Mapping

First, we'll create an array of objects that links each log/backup path to its corresponding display label. This makes it easy to iterate through all paths and automatically pull the right identifier without hardcoding logic for each path.

Step 2: Refactor the Cleanup Function

We'll turn your existing code into a function that accepts two key parameters: the friendly identifier (e.g., "Jira - Logs") and the target path. This function will handle outputting the section headers first, then run your existing file cleanup and list display logic—keeping everything aligned with your desired structure.

Step 3: Iterate Through All Paths

Loop through our mapping, call the cleanup function for each entry, and let it handle the real-time display and logging seamlessly.

Here's the complete implementation tailored to your needs:

# Define the path-to-identifier mapping - add/remove entries as needed
$pathMappings = @(
    @{ Identifier = "Jira - Logs"; Path = "C:\Program Files\Atlassian\JIRA\logs\" },
    @{ Identifier = "Confluence - Logs"; Path = "C:\Program Files\Atlassian\Confluence\logs\" },
    @{ Identifier = "Bitbucket - Logs"; Path = "C:\Atlassian\ApplicationData\Bitbucket\log" },
    @{ Identifier = "Bitbucket - Backups"; Path = "C:\Atlassian\bitbucket-backup-client-4.0.0\backups\" }
)

# Configure your log paths
$transcriptPath = "log path" # Replace with your actual transcript file path
$housekeepLogPath = "E:\backup\housekeep_log\Housekeep.log"

# Start transcript logging once before processing all paths
Start-Transcript -Path $transcriptPath -Append # Use -Append to avoid overwriting existing logs

# Reusable cleanup function with identifier support
function Invoke-PathCleanup {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Identifier,
        [Parameter(Mandatory=$true)]
        [string]$Path,
        [int]$KeepCount = 5 # Adjust this to your desired number of files to retain
    )

    # Output section header (visible in console and transcript)
    Write-Host "`n=== $Identifier ===" -ForegroundColor Cyan
    Write-Output "`n=== $Identifier ==="

    # Get all files in the target path, sorted by last modified time (oldest first)
    $files = Get-ChildItem -Path $Path -File | Sort-Object LastWriteTime

    if ($files.Count -gt 0) {
        # Display and log non-deleted files (the ones we're keeping)
        Write-Host "`n未删除文件列表" -ForegroundColor Green
        Write-Output "`n未删除文件列表"
        $filesToKeep = $files | Select-Object -Last $KeepCount
        foreach ($file in $filesToKeep) {
            Write-Host $file.FullName
            Write-Output $file.FullName
        }

        # Calculate files marked for deletion
        $filesToDelete = $files | Select-Object -First ($files.Count - $KeepCount)
        if ($filesToDelete.Count -gt 0) {
            # Display and log deleted files
            Write-Host "`n已删除文件列表" -ForegroundColor Yellow
            Write-Output "`n已删除文件列表"
            foreach ($file in $filesToDelete) {
                Write-Host $file.FullName
                Write-Output $file.FullName
                $file.FullName | Add-Content -Path $housekeepLogPath
            }

            # Uncomment the line below when you're ready to actually delete files
            # $filesToDelete | Remove-Item -Force
            Write-Host "`nDeleted $($filesToDelete.Count) files from $Path`n" -ForegroundColor Red
            Write-Output "`nDeleted $($filesToDelete.Count) files from $Path`n"
        } else {
            Write-Host "`nNo files to delete - keeping all $($files.Count) files`n" -ForegroundColor Green
            Write-Output "`nNo files to delete - keeping all $($files.Count) files`n"
        }
    } else {
        Write-Host "`nNo files found in $Path`n" -ForegroundColor Gray
        Write-Output "`nNo files found in $Path`n"
    }
}

# Process each path in the mapping
foreach ($mapping in $pathMappings) {
    Invoke-PathCleanup -Identifier $mapping.Identifier -Path $mapping.Path -KeepCount 5 # Adjust KeepCount as needed
}

# Stop transcript logging after all paths are processed
Stop-Transcript

Key Details:

  • Flexible Mapping: The $pathMappings array lets you easily add new paths or modify existing ones without touching the core cleanup logic.
  • Real-Time Visibility: We use Write-Host with color coding for immediate console feedback (great for monitoring runs) and Write-Output to ensure all content is captured in the transcript.
  • Safety First: The actual file deletion line is commented out—uncomment it only after you've verified the output matches your expectations.
  • Clean Structure: The function encapsulates all repetitive logic, keeping your script organized and easy to maintain.

This will output exactly the structure you requested, in real-time as each path is processed, while also logging everything to your transcript and housekeep log.

内容的提问来源于stack exchange,提问作者ontljoshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 16:48:12