Экстрактор пути к файлу:

Переводчик Google

Malnutrition

Разработчик
Сообщения
402
Реакции
58
Перетащите файл .txt: FRST.txt Addition.txt или что-то еще.





Код:
Add-Type -AssemblyName System.Windows.Forms


$global:pathPatterns = @(
    # Pattern to match paths with Program Files or Program Files (x86) and multiple subdirectories, optionally ending with file extensions
    '(?i)([A-Za-z]:\\(?:Program Files(?:\s*\(x86\))?|Windows|Users|AppData|ProgramData|WindowsApps|System32|SysWOW64|Common Files)(?:\\[^\\/:*?"<>|\r\n]+)*\\[^\\/:*?"<>|\r\n]+(?:\.[a-zA-Z0-9]{1,10})?)',
    
    # General pattern to match paths with multiple subdirectories, optionally ending with file extensions
    '(?i)([A-Za-z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]+(?:\.[a-zA-Z0-9]{1,10})?)',
    
    # Pattern to match UNC paths with multiple subdirectories, optionally ending with file extensions
    '(?i)(\\\\[^\s:*?"<>|\r\n]+\\[^\s:*?"<>|\r\n]+(?:\\[^\\/:*?"<>|\r\n]+)*(?:\.[a-zA-Z0-9]{1,10})?)'
)


$form = New-Object System.Windows.Forms.Form
$form.Text = "File Path Extraction Tool"
$form.Width = 800
$form.Height = 700
$form.AllowDrop = $true


$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Multiline = $true
$textBox.Dock = "Top"
$textBox.Height = 300
$textBox.ScrollBars = "Both"
$textBox.MaxLength = 2147483647
$form.Controls.Add($textBox)


$pathListBox = New-Object System.Windows.Forms.ListBox
$pathListBox.Dock = "Fill"
$pathListBox.Height = 200
$form.Controls.Add($pathListBox)

$copyPasteButton = New-Object System.Windows.Forms.Button
$copyPasteButton.Text = "Copy and Paste Input"
$copyPasteButton.Dock = "Top"
$copyPasteButton.Height = 30
$copyPasteButton.Add_Click({
    $textBox.Text = [System.Windows.Forms.Clipboard]::GetText()
})
$form.Controls.Add($copyPasteButton)


$clearButton = New-Object System.Windows.Forms.Button
$clearButton.Text = "Clear"
$clearButton.Dock = "Top"
$clearButton.Height = 30
$clearButton.Add_Click({
    $textBox.Clear()
    $pathListBox.Items.Clear()
})
$form.Controls.Add($clearButton)


$outputFilePathTextBox = New-Object System.Windows.Forms.TextBox
$outputFilePathTextBox.Dock = "Top"
$outputFilePathTextBox.Height = 30
$outputFilePathTextBox.Text = [System.Environment]::GetFolderPath('Desktop') + "\filepaths.txt"
$form.Controls.Add($outputFilePathTextBox)


class PathExtractor {
    static [void] WriteDebugLog([string]$message, [string]$debugPath) {
        try {
            $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            $logMessage = "$timestamp - $message`n"
            $logMessage | Out-File -FilePath $debugPath -Append -Encoding UTF8
        }
        catch {
            
            [System.Windows.Forms.MessageBox]::Show(
                "Debug logging failed: $($_.Exception.Message)", 
                "Debug Error", 
                [System.Windows.Forms.MessageBoxButtons]::OK, 
                [System.Windows.Forms.MessageBoxIcon]::Warning
            )
        }
    }

    static [void] CleanSystem32DllPaths([string[]]$lines, [System.Collections.Generic.HashSet[string]]$filePaths, [string]$debugPath) {
        $system32DllPattern = '(?i)(C:\\Windows\\System32(?:\\[^\\/:*?"<>|\r\n]+)*\\[^\\/:*?"<>|\r\n]+\.(dll|exe))'

        foreach ($line in $lines) {
            if ($line -match $system32DllPattern) {
                $filePathMatch = $matches[1].Trim()
                
                if (-not [string]::IsNullOrWhiteSpace($filePathMatch)) {
                    $filePaths.Add($filePathMatch) | Out-Null
                    [PathExtractor]::WriteDebugLog("System32 DLL/EXE Path Added: $filePathMatch", $debugPath)
                }
            }
        }
    }

    static [string] CleanPath([string]$originalPath, [string]$debugPath) {
    if ([string]::IsNullOrWhiteSpace($originalPath)) {
        return $originalPath
    }

    
    [PathExtractor]::WriteDebugLog("Original path before cleaning: $originalPath", $debugPath)

    
    $cleanPath = [regex]::Replace($originalPath, '^O\d+\s*-\s*[^:]*:\s*', '', 'IgnoreCase')

    
    $cleanPath = $cleanPath -replace 'Program Files\s*\(x86\)', 'Program Files (x86)'

    
    $cleanPath = [regex]::Replace($cleanPath, '^.*?([A-Za-z]:\\.*)', '$1', 'IgnoreCase')

    
    $cleanPath = [regex]::Replace($cleanPath, '(?i)\s*=>.*$', '', 'IgnoreCase')

    
    $cleanPath = [regex]::Replace($cleanPath, '\s*\[Unsigned\]', '', 'IgnoreCase')
    $cleanPath = [regex]::Replace($cleanPath, '\s*\[.*?\]', '', 'IgnoreCase')

    
    $cleanPath = [regex]::Replace($cleanPath, '(?i)^O\d+\s*-\s*PUC:\s*".*?"\s*\[.*?\]\s*\.\s*', '', 'IgnoreCase')

    
    $cleanPath = [regex]::Replace($cleanPath, '--\s*', '', 'IgnoreCase')

    
    $cleanPath = [regex]::Replace($cleanPath, '\s*=+\s*$', '', 'IgnoreCase')

    
    $cleanPath = [regex]::Replace($cleanPath, '(\.[a-zA-Z0-9]{1,10})\b.*$', '$1', 'IgnoreCase') # Increased to 10 for longer extensions

    
    $cleanPath = $cleanPath.Trim()

    
    [PathExtractor]::WriteDebugLog("Cleaned path: $cleanPath", $debugPath)

    return $cleanPath
}


    static [string] FinalCleanPath([string]$path, [string]$debugPath) {
        if ([string]::IsNullOrWhiteSpace($path)) {
            return $path
        }

        
        [PathExtractor]::WriteDebugLog("Path before FinalCleanPath: $path", $debugPath)

        
        $path = $path -replace 'Program Files\s*\(x86\)', 'Program Files _X86_'

        
        $path = [regex]::Replace($path, '(\.[a-zA-Z0-9]{1,10})\b.*$', '$1', 'IgnoreCase')

        
        $path = [regex]::Replace($path, '\s*\[PID\.\d+\]', '', 'IgnoreCase')

        
        $path = [regex]::Replace($path, '\s*\([^)]*\)', '', 'IgnoreCase') # Remove anything within additional parentheses

        
        $path = $path -replace 'Program Files _X86_', 'Program Files (x86)'

        
        $path = $path.Trim()

        
        [PathExtractor]::WriteDebugLog("Path after FinalCleanPath: $path", $debugPath)

        return $path
    }

    static [string] RemoveCustomPatterns([string]$path, [string]$debugPath) {
        if ([string]::IsNullOrWhiteSpace($path)) {
            return $path
        }

        
        [PathExtractor]::WriteDebugLog("Path before custom cleaning: $path", $debugPath)

        

        
        $path = $path.Trim()

        
        [PathExtractor]::WriteDebugLog("Path after custom cleaning: $path", $debugPath)

        return $path
    }

    static [object] ExtractUniquePaths([string[]]$lines, [string[]]$pathPatterns, [string]$debugPath) {
       
        $uniquePaths = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase)

        
        [PathExtractor]::CleanSystem32DllPaths($lines, $uniquePaths, $debugPath)

        foreach ($line in $lines) {
            [PathExtractor]::WriteDebugLog("Processing line: $line", $debugPath)
            foreach ($pattern in $pathPatterns) {
                $matches = [regex]::Matches($line, $pattern)
                [PathExtractor]::WriteDebugLog("Pattern: $pattern - Matches Found: $($matches.Count)", $debugPath)
                foreach ($match in $matches) {
                    $originalPath = $match.Groups[1].Value
                    [PathExtractor]::WriteDebugLog("Original Path Found: $originalPath", $debugPath)
                    $cleanPath = [PathExtractor]::CleanPath($originalPath, $debugPath)
                    $cleanPath = [PathExtractor]::RemoveCustomPatterns($cleanPath, $debugPath)
                    $cleanPath = [PathExtractor]::FinalCleanPath($cleanPath, $debugPath) # Final cleanup

                    
                    if ($cleanPath -match '^C:\\Program Files \(x86\)\\WindowsApps\\') {
                        $cleanPath = [PathExtractor]::CleanWindowsAppsPath($cleanPath, $debugPath)
                    }

                    
                    if ($cleanPath.Length -ge 3 -and $cleanPath -match '^[A-Za-z]:\\') {
                        $uniquePaths.Add($cleanPath) | Out-Null
                        [PathExtractor]::WriteDebugLog("Path Added: $cleanPath", $debugPath)
                    }
                    else {
                        [PathExtractor]::WriteDebugLog("Path Skipped: $cleanPath", $debugPath)
                    }
                }
            }
        }

        
        return @{
            AllPaths = $uniquePaths
        }
    }

    static [void] LogExtraction(
        [System.Collections.Generic.HashSet[string]]$allPaths, 
        [string]$outputPath,
        [string]$debugPath
    ) {
        
        $extensionsToCategorize = @('.dll', '.sys', '.exe', '.bat', '.cmd', '.vbs', '.ps1') # Add more as needed

        
        $categorizedPaths = @{}
        foreach ($ext in $extensionsToCategorize) {
            $categorizedPaths[$ext] = @()
        }
        $categorizedPaths['Others'] = @()

        
        foreach ($path in $allPaths) {
            
            $ext = [System.IO.Path]::GetExtension($path).ToLower()
            if ($extensionsToCategorize -contains $ext) {
                $categorizedPaths[$ext] += $path
            }
            else {
                $categorizedPaths['Others'] += $path
            }
        }

        try {
            
            [PathExtractor]::WriteDebugLog("Starting log extraction", $debugPath)
            [PathExtractor]::WriteDebugLog("Output Path: $outputPath", $debugPath)
            [PathExtractor]::WriteDebugLog("Total Paths: $($allPaths.Count)", $debugPath)

            foreach ($ext in $extensionsToCategorize) {
                [PathExtractor]::WriteDebugLog("Paths with extension ${ext}: $($categorizedPaths[$ext].Count)", $debugPath)
            }
            [PathExtractor]::WriteDebugLog("Paths categorized as Others: $($categorizedPaths['Others'].Count)", $debugPath)

            
            $logContent = @"
Path Extraction Report
=====================
Total Unique Paths: $($allPaths.Count)
Extraction Timestamp: $(Get-Date)

"@

            foreach ($ext in $extensionsToCategorize) {
                $logContent += @"
${ext} Paths:
------------
"@
                if ($categorizedPaths[$ext].Count -gt 0) {
                    $logContent += ($categorizedPaths[$ext] -join "`n") + "`n`n"
                }
                else {
                    $logContent += "No entries found.`n`n"
                }
            }

            # Include 'Others' category for directory paths
            $logContent += @"
Others:
-------
"@
            if ($categorizedPaths['Others'].Count -gt 0) {
                $logContent += ($categorizedPaths['Others'] -join "`n") + "`n`n"
            }
            else {
                $logContent += "No entries found.`n`n"
            }

            
            $directory = [System.IO.Path]::GetDirectoryName($outputPath)
            if (-not (Test-Path -Path $directory)) {
                [System.IO.Directory]::CreateDirectory($directory)
                [PathExtractor]::WriteDebugLog("Created directory: $directory", $debugPath)
            }

            
            $logContent | Out-File -FilePath $outputPath -Encoding UTF8 -ErrorAction Stop
            [PathExtractor]::WriteDebugLog("Log file written successfully", $debugPath)

            
            [System.Windows.Forms.MessageBox]::Show(
                "Paths extracted and categorized successfully!`n`nFile saved to:`n$outputPath", 
                "Extraction Complete", 
                [System.Windows.Forms.MessageBoxButtons]::OK, 
                [System.Windows.Forms.MessageBoxIcon]::Information
            )
        }
        catch {
            
            [PathExtractor]::WriteDebugLog("Error in LogExtraction: $($_.Exception.Message)", $debugPath)
            [PathExtractor]::WriteDebugLog("Stack Trace: $($_.Exception.StackTrace)", $debugPath)

            [System.Windows.Forms.MessageBox]::Show(
                "Failed to write log file: $($_.Exception.Message)", 
                "Logging Error", 
                [System.Windows.Forms.MessageBoxButtons]::OK, 
                [System.Windows.Forms.MessageBoxIcon]::Warning
            )
        }
    }

    static [string] CleanWindowsAppsPath([string]$path, [string]$debugPath) {
        if ([string]::IsNullOrWhiteSpace($path)) {
            return $path
        }

        
        [PathExtractor]::WriteDebugLog("Path before cleaning: $path", $debugPath)

        
        $cleanPath = [regex]::Replace($path, ' - .*$', '', 'IgnoreCase')

        
        $cleanPath = $cleanPath.Trim()

        
        [PathExtractor]::WriteDebugLog("Cleaned path: $cleanPath", $debugPath)

        return $cleanPath
    }
}


$extractButton = New-Object System.Windows.Forms.Button
$extractButton.Text = "Extract File & Folder Paths"
$extractButton.Dock = "Top"
$extractButton.Height = 30

$extractButton.Add_Click({
    try {
        $ErrorActionPreference = 'Continue'
        
        
        $debugPath = [System.Environment]::GetFolderPath('Desktop') + "\pathextractor_debug.txt"

        
        if (Test-Path $debugPath) {
            Remove-Item $debugPath
        }

        
        [PathExtractor]::WriteDebugLog("Starting path extraction", $debugPath)

        $lines = $textBox.Text -split "`r?`n"

        [PathExtractor]::WriteDebugLog("Total lines: $($lines.Count)", $debugPath)

        
        $extractedPaths = [PathExtractor]::ExtractUniquePaths($lines, $global:pathPatterns, $debugPath)

        $allPaths = $extractedPaths.AllPaths

        [PathExtractor]::WriteDebugLog("Total Unique Paths: $($allPaths.Count)", $debugPath)

        
        $pathListBox.Items.Clear()
        foreach ($path in $allPaths) {
            $pathListBox.Items.Add($path) | Out-Null
        }

        
        $outputPath = $outputFilePathTextBox.Text

        
        [PathExtractor]::LogExtraction($allPaths, $outputPath, $debugPath)
    }
    catch {
        
        $debugPath = [System.Environment]::GetFolderPath('Desktop') + "\pathextractor_debug.txt"
        [PathExtractor]::WriteDebugLog("Unhandled error: $($_.Exception.Message)", $debugPath)
        [PathExtractor]::WriteDebugLog("Stack Trace: $($_.Exception.StackTrace)", $debugPath)

        [System.Windows.Forms.MessageBox]::Show(
            "Unexpected error: $($_.Exception.Message)", 
            "Extraction Error", 
            [System.Windows.Forms.MessageBoxButtons]::OK, 
            [System.Windows.Forms.MessageBoxIcon]::Error
        )
    }
})
$form.Controls.Add($extractButton)


$form.Add_DragEnter({
    if ($_.Data.GetDataPresent([Windows.Forms.DataFormats]::FileDrop)) {
        $_.Effect = [Windows.Forms.DragDropEffects]::Copy
    }
})


$form.Add_DragDrop({
    $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop)
    foreach ($file in $files) {
        if ($file -match '\.(txt|log|csv|json|md|html|htm|xml)$') {
            try {
                $content = Get-Content -Path $file -Raw -Encoding UTF8
                if ($textBox.Text.Length -gt 0 -and !$textBox.Text.EndsWith("`n")) {
                    $textBox.AppendText("`n")
                }
                $textBox.AppendText($content)
                $textBox.AppendText("`n")  # Add a new line for separation
            }
            catch {
                [System.Windows.Forms.MessageBox]::Show("Failed to read file: $file`n`nError: $($_.Exception.Message)", "File Read Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
            }
        }
        elseif (Test-Path -Path $file -PathType Container) {
            try {
                $content = Get-ChildItem -Path $file -Recurse -File -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName }
                if ($textBox.Text.Length -gt 0 -and !$textBox.Text.EndsWith("`n")) {
                    $textBox.AppendText("`n")
                }
                $textBox.AppendText([string]::Join("`n", $content))
                $textBox.AppendText("`n")  # Add a new line for separation
            }
            catch {
                [System.Windows.Forms.MessageBox]::Show("Failed to read directory: $file`n`nError: $($_.Exception.Message)", "Directory Read Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
            }
        }
        else {
            [System.Windows.Forms.MessageBox]::Show("Only .txt, .log, .csv, .json, .md, and .html files are supported.", "Unsupported File Type", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning)
        }
    }
})

$form.ShowDialog()
 
  • Like
Реакции: akok
Я потратил на это слишком много времени.Но это работает...:Dance4:
 
Назад
Сверху Снизу