PowerSHELL İle Hassas Dosya Arama

Programlama ve Script dilleri konusunda bilgi paylaşım alanıdır.
Cevapla
Kullanıcı avatarı
TRWE_2012
Zettabyte1
Zettabyte1
Mesajlar: 15551
Kayıt: 25 Eyl 2013, 13:38
cinsiyet: Erkek
Teşekkür etti: 2695 kez
Teşekkür edildi: 5578 kez

PowerSHELL İle Hassas Dosya Arama

Mesaj gönderen TRWE_2012 »

Merhabalar...

İnternet kesikken uğraştığım betik, güle güle kullanın...

Ama önce konu anlatımı + örnek...
Resim
KOD İÇERİKLERİ :

Find-Files-By-Size-And-Name.ps1

Kod: Tümünü seç

# ============================================================
# Find Files by Size and Name
# System : Windows 11
# ============================================================

Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()

# --- DIRECTORY SELECTION WINDOW ---
$dlg = New-Object System.Windows.Forms.FolderBrowserDialog
$dlg.Description = "Select a directory"
if ($dlg.ShowDialog() -ne [System.Windows.Forms.DialogResult]::OK) {
    Write-Host "Directory selection cancelled."
    Read-Host "`nPress ENTER to exit."
    exit 1
}
$directory = $dlg.SelectedPath

# --- SIZE INPUT WINDOW ---
$sizeCondition = [Microsoft.VisualBasic.Interaction]::InputBox(
    "Size (e.g. +500M, -500M, =500M)`n`nNote: Size units:`n- B: Byte`n- K: Kilobyte`n- M: Megabyte`n- G: Gigabyte`n- T: Terabyte`n`n(For '=', a +/-5% tolerance is applied automatically, since an exact byte match is rarely meaningful.)",
    "Size Input",
    ""
)
if ([string]::IsNullOrWhiteSpace($sizeCondition)) {
    Write-Host "Size input cancelled."
    Read-Host "`nPress ENTER to exit."
    exit 1
}

# --- FILENAME CONDITION INPUT WINDOW ---
$filenameCondition = [Microsoft.VisualBasic.Interaction]::InputBox(
    "Filename condition (e.g. *.txt):",
    "Filename Condition",
    "*"
)
if ([string]::IsNullOrWhiteSpace($filenameCondition)) {
    Write-Host "Filename condition input cancelled."
    Read-Host "`nPress ENTER to exit."
    exit 1
}

# --- PROCESS THE SIZE CONDITION ---
$sizeOperator = $sizeCondition.Substring(0, 1)
$sizeValueRaw = $sizeCondition.Substring(1)

if ($sizeOperator -notin @('+', '-', '=')) {
    [System.Windows.Forms.MessageBox]::Show(
        "Invalid size input. Please start with +, - or =.",
        "Error",
        [System.Windows.Forms.MessageBoxButtons]::OK,
        [System.Windows.Forms.MessageBoxIcon]::Error
    ) | Out-Null
    Read-Host "`nPress ENTER to exit."
    exit 1
}

# Parse the numeric value and unit (e.g. "500M" -> 500 and "M").
# Culture-safe: accepts both '.' and ',' as decimal separator, always
# parsed as invariant (avoids the tr-TR comma/period pitfall).
if ($sizeValueRaw -notmatch '^(\d+(?:[.,]\d+)?)\s*([BKMGT])$') {
    [System.Windows.Forms.MessageBox]::Show(
        "Invalid size format. Example: 500M",
        "Error",
        [System.Windows.Forms.MessageBoxButtons]::OK,
        [System.Windows.Forms.MessageBoxIcon]::Error
    ) | Out-Null
    Read-Host "`nPress ENTER to exit."
    exit 1
}

$normalizedValue = $Matches[1] -replace ',', '.'
$numericValue = [double]::Parse($normalizedValue, [System.Globalization.CultureInfo]::InvariantCulture)
$unit = $Matches[2]

$unitMultiplier = switch ($unit) {
    'B' { 1 }
    'K' { 1KB }
    'M' { 1MB }
    'G' { 1GB }
    'T' { 1TB }
}

$sizeInBytes = $numericValue * $unitMultiplier

# --- FIND FILES MATCHING THE SPECIFIED SIZE AND NAME CONDITION ---
Write-Host "Searching, this may take a moment for large directories..." -ForegroundColor Yellow

try {
    $allMatches = Get-ChildItem -LiteralPath $directory -File -Recurse -Filter $filenameCondition -ErrorAction SilentlyContinue

    $results = switch ($sizeOperator) {
        '+' { $allMatches | Where-Object { $_.Length -gt $sizeInBytes } }
        '-' { $allMatches | Where-Object { $_.Length -lt $sizeInBytes } }
        '=' {
            # Exact byte-for-byte match is rarely useful in practice - apply a
            # +/-5% tolerance band around the target size instead.
            $lowerBound = $sizeInBytes * 0.95
            $upperBound = $sizeInBytes * 1.05
            $allMatches | Where-Object { $_.Length -ge $lowerBound -and $_.Length -le $upperBound }
        }
    }

    # Sort largest-first - the most relevant order for reviewing search results
    $results = @($results | Sort-Object -Property Length -Descending)
} catch {
    [System.Windows.Forms.MessageBox]::Show(
        "An error occurred while searching.`n$($_.Exception.Message)",
        "Error",
        [System.Windows.Forms.MessageBoxButtons]::OK,
        [System.Windows.Forms.MessageBoxIcon]::Error
    ) | Out-Null
    Read-Host "`nPress ENTER to exit."
    exit 1
}

# --- SHOW RESULTS IN A SCROLLABLE WINDOW ---
function Show-ResultsWindow {
    param([array]$Files)

    $totalBytes = ($Files | Measure-Object -Property Length -Sum).Sum
    $totalMB = [math]::Round($totalBytes / 1MB, 2)

    $form = New-Object System.Windows.Forms.Form
    $form.Text = "Search Results"
    $form.Width = 720
    $form.Height = 480
    $form.StartPosition = "CenterScreen"

    $summaryLabel = New-Object System.Windows.Forms.Label
    $summaryLabel.Text = "Found $($Files.Count) file(s), totaling $totalMB MB, in: $directory"
    $summaryLabel.Dock = "Top"
    $summaryLabel.Height = 35
    $summaryLabel.Padding = New-Object System.Windows.Forms.Padding(8, 8, 8, 0)
    $form.Controls.Add($summaryLabel)

    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Multiline = $true
    $textBox.ReadOnly = $true
    $textBox.WordWrap = $true
    $textBox.ScrollBars = "Vertical"
    $textBox.Dock = "Fill"
    $textBox.Font = New-Object System.Drawing.Font("Consolas", 9)
    $textBox.ForeColor = [System.Drawing.Color]::Black
    $textBox.BackColor = [System.Drawing.Color]::White

    if ($Files.Count -eq 0) {
        $lines = @("", "", "No files found.", "")
    } else {
        $lines = @("", "") + ($Files | ForEach-Object {
            $sizeMB = [math]::Round($_.Length / 1MB, 2)
            "$($_.FullName)  ($sizeMB MB)"
        }) + @("")
    }
    $textBox.Text = ($lines -join "`r`n")
    $form.Controls.Add($textBox)

    $buttonPanel = New-Object System.Windows.Forms.Panel
    $buttonPanel.Dock = "Bottom"
    $buttonPanel.Height = 45
    $form.Controls.Add($buttonPanel)

    if ($Files.Count -gt 0) {
        $exportButton = New-Object System.Windows.Forms.Button
        $exportButton.Text = "Export to CSV"
        $exportButton.Location = New-Object System.Drawing.Point(10, 8)
        $exportButton.Width = 120
        $exportButton.Add_Click({
            $desktop = [Environment]::GetFolderPath("Desktop")
            $csvPath = Join-Path $desktop "FileSearchResults_$(Get-Date -Format yyyyMMdd_HHmmss).csv"
            $Files | Select-Object FullName, @{N='SizeMB';E={[math]::Round($_.Length / 1MB, 2)}}, LastWriteTime |
                Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
            [System.Windows.Forms.MessageBox]::Show("Exported to:`n$csvPath", "Export Complete", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) | Out-Null
        })
        $buttonPanel.Controls.Add($exportButton)
    }

    $closeButton = New-Object System.Windows.Forms.Button
    $closeButton.Text = "Close"
    $closeButton.Location = New-Object System.Drawing.Point(600, 8)
    $closeButton.Width = 90
    $closeButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $buttonPanel.Controls.Add($closeButton)
    $form.AcceptButton = $closeButton

    $form.ShowDialog() | Out-Null
}

Show-ResultsWindow -Files $results

Read-Host "`nPress ENTER to exit."
Sağlama Kodlaması :

Kod: Tümünü seç

Get-ChildItem -Path "**BURAYA DİZİN ADINI YAZIN**" -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.Length -gt **BURAYA SAYISAL DEĞER YAZIN**MB } | Measure-Object | Select-Object Count
Kullanıcı avatarı
burak35
Zettabyte4
Zettabyte4
Mesajlar: 18100
Kayıt: 07 Eki 2016, 13:06
cinsiyet: Erkek
Teşekkür etti: 10508 kez
Teşekkür edildi: 12271 kez

Re: PowerSHELL İle Hassas Dosya Arama

Mesaj gönderen burak35 »

geçen gün zamanlanmış görevlerin çıktısını almam lazımdı. chatgpt ye sorayım dedim. google dan bakmakla uğraşamadım.
dedim bana zamanlanmış görevlerin çıktısını veren bi vbs yaz. o da dedi powershell vereyim daha iyi olur.
bende dedim iyi o zaman powershell ver bakalım. o da bir sevindi bir sevindi anlatamam. :)
gelmiş bana powershell övüyo ya ? :d sanki mükemmel birşey powershell :) ha işimi gördü tabi o ayrı.
Kullanıcı avatarı
TRWE_2012
Zettabyte1
Zettabyte1
Mesajlar: 15551
Kayıt: 25 Eyl 2013, 13:38
cinsiyet: Erkek
Teşekkür etti: 2695 kez
Teşekkür edildi: 5578 kez

Re: PowerSHELL İle Hassas Dosya Arama

Mesaj gönderen TRWE_2012 »

burak35 yazdı: 15 Ağu 2026, 11:16 geçen gün zamanlanmış görevlerin çıktısını almam lazımdı. chatgpt ye sorayım dedim. google dan bakmakla uğraşamadım.
dedim bana zamanlanmış görevlerin çıktısını veren bi vbs yaz. o da dedi powershell vereyim daha iyi olur.
bende dedim iyi o zaman powershell ver bakalım. o da bir sevindi bir sevindi anlatamam. :)
gelmiş bana powershell övüyo ya ? :d sanki mükemmel birşey powershell :) ha işimi gördü tabi o ayrı.
:-D
Cevapla

“Programlama ve Script dilleri” sayfasına dön