Dosya İlişkilendirme PS1 Betiği

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

Dosya İlişkilendirme PS1 Betiği

Mesaj gönderen TRWE_2012 »

Merhabalar
Resim

Kod: Tümünü seç

REG ADD "HKEY_CLASSES_ROOT\Applications\FlashPlayer.exe\shell\open\command" /v @ /t REG_SZ /d "\"D:\\PRG\FlashPlayer\\FlashPlayer.exe\" \"%%1\"" /f
REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Classes\swffile\DefaultIcon" /t REG_SZ /d "D:\PRG\FlashPlayer\FlashPlayer.exe,0" /f
REG ADD "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.swf" /v "Application" /t REG_SZ /d "FlashPlayer.exe" /f
REG ADD "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.swf\OpenWithList" /v "g" /t REG_SZ /d "FlashPlayer.exe" /f

assoc .swf=swffile
ftype swffile=D:\PRG\FlashPlayer\FlashPlayer.exe %%1
Bu betik, forum'daki bir konudan alıntı'nın örnek reg kaydından alınmış , "reg add, assoc, ftype" tipinden oluşan bir bat örneğinin günümüz madern sistemlerine uyarlanmış halidir.

dosya-iliskilendirme-yonetici_v2.ps1 Betiğinin İçeriği :

Kod: Tümünü seç

<#
    dosya-iliskilendirme-yonetici.ps1

    Purpose:
        Menu-driven file type association manager, generalizing the classic
        "reg add / assoc / ftype" batch approach into a reusable PowerShell
        tool with three operations:
            1) Associate a file extension with a chosen program
            2) Reset a file extension's association back to a given default program
            3) Permanently remove a file extension's association from the registry
            4) Exit

    Registry locations touched (mirrors the original batch file's logic):
        HKEY_CLASSES_ROOT\Applications\<exeName>\shell\open\command
        HKEY_LOCAL_MACHINE\SOFTWARE\Classes\<progId>\DefaultIcon
        HKEY_LOCAL_MACHINE\SOFTWARE\Classes\<progId>\shell\open\command   (ftype equivalent)
        HKEY_CLASSES_ROOT\<extension>                                    (assoc equivalent)
        HKEY_CURRENT_USER\...\Explorer\FileExts\<extension>\Application
        HKEY_CURRENT_USER\...\Explorer\FileExts\<extension>\OpenWithList

    Known limitation (same one already observed by the user):
        Windows may accept this association change but the Explorer icon
        shown for that file type can fail to refresh immediately. This is a
        long-standing Explorer icon cache behavior, not something the
        registry writes below can fully control on their own.

    Requires: Administrator privileges (the script self-elevates if needed),
              because HKEY_LOCAL_MACHINE and HKEY_CLASSES_ROOT writes need it.
#>

$ErrorActionPreference = "Stop"

# ---------------------------------------------------------------------------
# Self-elevate if not already running as Administrator
# ---------------------------------------------------------------------------
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process powershell.exe -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "`"$PSCommandPath`"" -Verb RunAs
    exit
}

# Make sure the HKCR: PSDrive exists (not mounted by default in PowerShell)
if (-not (Get-PSDrive -Name HKCR -ErrorAction SilentlyContinue)) {
    New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT -ErrorAction SilentlyContinue | Out-Null
}

# ---------------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------------

function Get-NormalizedExtension {
    param([string]$Extension)
    $ext = $Extension.Trim()
    if (-not $ext.StartsWith(".")) {
        $ext = ".$ext"
    }
    return $ext.ToLower()
}

function Get-ProgIdForExtension {
    param([string]$Extension)
    $bare = $Extension.TrimStart(".")
    # Suffixed to avoid overwriting Windows' own built-in ProgIds
    # (e.g. plain "txtfile" or "htmlfile" already exist and are used by the OS).
    return "$($bare)file.Custom"
}

function Set-FileAssociation {
    param(
        [Parameter(Mandatory)][string]$Extension,
        [Parameter(Mandatory)][string]$ExecutablePath
    )

    $exeName = Split-Path -Path $ExecutablePath -Leaf
    $progId  = Get-ProgIdForExtension -Extension $Extension
    $openCommand = "`"$ExecutablePath`" `"%1`""

    # HKCR\Applications\<exeName>\shell\open\command
    $appCommandPath = "HKCR:\Applications\$exeName\shell\open\command"
    if (-not (Test-Path $appCommandPath)) {
        New-Item -Path $appCommandPath -Force | Out-Null
    }
    Set-Item -Path $appCommandPath -Value $openCommand

    # HKLM\SOFTWARE\Classes\<progId>\DefaultIcon
    $iconPath = "HKLM:\SOFTWARE\Classes\$progId\DefaultIcon"
    if (-not (Test-Path $iconPath)) {
        New-Item -Path $iconPath -Force | Out-Null
    }
    Set-Item -Path $iconPath -Value "$ExecutablePath,0"

    # HKLM\SOFTWARE\Classes\<progId>\shell\open\command  (ftype equivalent)
    $progCommandPath = "HKLM:\SOFTWARE\Classes\$progId\shell\open\command"
    if (-not (Test-Path $progCommandPath)) {
        New-Item -Path $progCommandPath -Force | Out-Null
    }
    Set-Item -Path $progCommandPath -Value $openCommand

    # HKCR\<extension>  (assoc equivalent: .ext -> progId)
    $extPath = "HKCR:\$Extension"
    if (-not (Test-Path $extPath)) {
        New-Item -Path $extPath -Force | Out-Null
    }
    Set-Item -Path $extPath -Value $progId

    # HKCU\...\Explorer\FileExts\<extension>\Application
    $fileExtsPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$Extension"
    if (-not (Test-Path $fileExtsPath)) {
        New-Item -Path $fileExtsPath -Force | Out-Null
    }
    Set-ItemProperty -Path $fileExtsPath -Name "Application" -Value $exeName

    # HKCU\...\Explorer\FileExts\<extension>\OpenWithList
    $openWithListPath = Join-Path $fileExtsPath "OpenWithList"
    if (-not (Test-Path $openWithListPath)) {
        New-Item -Path $openWithListPath -Force | Out-Null
    }
    Set-ItemProperty -Path $openWithListPath -Name "a" -Value $exeName
}

function Set-DefaultAppViaDism {
    param(
        [Parameter(Mandatory)][string]$Extension,
        [Parameter(Mandatory)][string]$ProgId,
        [Parameter(Mandatory)][string]$ApplicationName
    )

    $xmlPath = Join-Path $env:TEMP "defaultassoc_$([guid]::NewGuid().ToString('N')).xml"
    $xmlContent = @"
<?xml version="1.0" encoding="UTF-8"?>
<DefaultAssociations>
    <Association Identifier="$Extension" ProgId="$ProgId" ApplicationName="$ApplicationName" />
</DefaultAssociations>
"@
    Set-Content -Path $xmlPath -Value $xmlContent -Encoding UTF8

    try {
        $output = & dism.exe /Online /Import-DefaultAppAssociations:"$xmlPath" 2>&1
        $exitCode = $LASTEXITCODE
        return [PSCustomObject]@{
            Success  = ($exitCode -eq 0)
            ExitCode = $exitCode
            Output   = ($output | Out-String)
        }
    }
    catch {
        return [PSCustomObject]@{
            Success  = $false
            ExitCode = -1
            Output   = "$_"
        }
    }
    finally {
        Remove-Item -Path $xmlPath -Force -ErrorAction SilentlyContinue
    }
}

function Remove-FileAssociation {
    param(
        [Parameter(Mandatory)][string]$Extension,
        [Parameter(Mandatory)][string]$ExecutablePath
    )

    $exeName = Split-Path -Path $ExecutablePath -Leaf
    $progId  = Get-ProgIdForExtension -Extension $Extension

    $pathsToRemove = @(
        "HKCR:\Applications\$exeName",
        "HKLM:\SOFTWARE\Classes\$progId",
        "HKCR:\$Extension",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$Extension"
    )

    foreach ($path in $pathsToRemove) {
        if (Test-Path $path) {
            Remove-Item -Path $path -Recurse -Force -ErrorAction SilentlyContinue
        }
    }
}

function Show-Menu {
    Write-Host "==================================================================================================="
    Write-Host "Dosya Format - Yazilim Dosya Iliskilendirme Yoneticisine Hosgeldiniz."
    Write-Host "==================================================================================================="
    Write-Host ""
    Write-Host "Ne yapmak istiyoruz...?!"
    Write-Host ""
    Write-Host "1 = Dosya Format-Yazilim Dosya Iliskilendirmesi"
    Write-Host "2 = Dosya Format - Yazilim Dosya Iliskilendirmesi Varsayilan'a Donus"
    Write-Host "3 = Dosya Format - Yazilim Dosya Iliskilendirmesini Kayit Defterinden `"KALICI SILME`""
    Write-Host "4 = Betik Cikis"
    Write-Host ""
}

function Wait-ForMenuReturn {
    while ($true) {
        $choice = Read-Host "Ana Menuye donmek icin R, betikten cikmak icin E tusuna basin klavyeden"
        switch ($choice.ToUpper()) {
            "R" { return $true }
            "E" { return $false }
            default { Write-Host "Gecersiz secim, lutfen R veya E girin." -ForegroundColor Yellow }
        }
    }
}

# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------

$keepRunning = $true

while ($keepRunning) {
    Clear-Host
    Show-Menu

    $selection = Read-Host "Lutfen Seciminizi Klavyeden Gir Ve Enter'a Bas"

    switch ($selection) {
        "1" {
            Write-Host ""
            Write-Host "Dosya Format-Yazilim Dosya Iliskilendirmesi secildi..."
            Write-Host ""
            $ext = Read-Host "Dosya Uzantisi Gir"
            $ext = Get-NormalizedExtension -Extension $ext
            $exePath = Read-Host "Iliskilendirilecek Yazilimin Tam Yolunu Gir"

            if (-not (Test-Path $exePath)) {
                Write-Host ""
                Write-Host "UYARI: Belirtilen yol bulunamadi, yine de devam ediliyor." -ForegroundColor Yellow
            }

            try {
                Set-FileAssociation -Extension $ext -ExecutablePath $exePath
                Write-Host ""
                Write-Host "$ext dosya formati, $(Split-Path $exePath -Leaf) ile iliskilendirilme islemi... [BASARILI]" -ForegroundColor Green

                $progId = Get-ProgIdForExtension -Extension $ext
                $appName = [System.IO.Path]::GetFileNameWithoutExtension($exePath)
                Write-Host ""
                Write-Host "Cift tiklamada dogrudan acilmasi icin DISM ile varsayilan atanmaya calisiliyor..."
                $dismResult = Set-DefaultAppViaDism -Extension $ext -ProgId $progId -ApplicationName $appName
                if ($dismResult.Success) {
                    Write-Host "Varsayilan uygulama DISM ile basariyla atandi. Artik 'Nasil acmak istersiniz' penceresi cikmamali." -ForegroundColor Green
                }
                else {
                    Write-Host "DISM ile otomatik atama basarisiz oldu (cikis kodu: $($dismResult.ExitCode))." -ForegroundColor Yellow
                    Write-Host "Bu bilinen bir Windows kisitidir. Cozum: bir dosyaya cift tikladiginizda cikan pencerede" -ForegroundColor Yellow
                    Write-Host "$appName secip 'Her zaman' tusuna bir kez basmaniz yeterli." -ForegroundColor Yellow
                }
            }
            catch {
                Write-Host ""
                Write-Host "Islem basarisiz oldu: $_" -ForegroundColor Red
            }

            Write-Host ""
            $keepRunning = Wait-ForMenuReturn
        }

        "2" {
            Write-Host ""
            Write-Host "Dosya Format - Yazilim Dosya Iliskilendirmesi Varsayilan'a Donus secildi."
            Write-Host ""
            $ext = Read-Host "Dosya Uzantisi Gir"
            $ext = Get-NormalizedExtension -Extension $ext
            $exePath = Read-Host "Iliskilendirilecek Varsayilan Yazilimin Tam Yolunu Gir"

            if (-not (Test-Path $exePath)) {
                Write-Host ""
                Write-Host "UYARI: Belirtilen yol bulunamadi, yine de devam ediliyor." -ForegroundColor Yellow
            }

            try {
                Set-FileAssociation -Extension $ext -ExecutablePath $exePath
                Write-Host ""
                Write-Host "$ext dosya formati, varsayilan yazilimla acilacak sekilde varsayilan'a donduruldu. [BASARILI]" -ForegroundColor Green

                $progId = Get-ProgIdForExtension -Extension $ext
                $appName = [System.IO.Path]::GetFileNameWithoutExtension($exePath)
                Write-Host ""
                Write-Host "Cift tiklamada dogrudan acilmasi icin DISM ile varsayilan atanmaya calisiliyor..."
                $dismResult = Set-DefaultAppViaDism -Extension $ext -ProgId $progId -ApplicationName $appName
                if ($dismResult.Success) {
                    Write-Host "Varsayilan uygulama DISM ile basariyla atandi. Artik 'Nasil acmak istersiniz' penceresi cikmamali." -ForegroundColor Green
                }
                else {
                    Write-Host "DISM ile otomatik atama basarisiz oldu (cikis kodu: $($dismResult.ExitCode))." -ForegroundColor Yellow
                    Write-Host "Bu bilinen bir Windows kisitidir. Cozum: bir dosyaya cift tikladiginizda cikan pencerede" -ForegroundColor Yellow
                    Write-Host "$appName secip 'Her zaman' tusuna bir kez basmaniz yeterli." -ForegroundColor Yellow
                }
            }
            catch {
                Write-Host ""
                Write-Host "Islem basarisiz oldu: $_" -ForegroundColor Red
            }

            Write-Host ""
            $keepRunning = Wait-ForMenuReturn
        }

        "3" {
            Write-Host ""
            Write-Host "Dosya Format - Yazilim Dosya Iliskilendirmesini Kayit Defterinden `"KALICI SILME`" [DIKKAT..!]" -ForegroundColor Yellow
            Write-Host ""
            $ext = Read-Host "Dosya Uzantisi Gir"
            $ext = Get-NormalizedExtension -Extension $ext
            $exePath = Read-Host "Iliskilendirilecek Yazilimin Tam Yolunu Gir"

            try {
                Remove-FileAssociation -Extension $ext -ExecutablePath $exePath
                Write-Host ""
                Write-Host "Artik $ext dosya formati, $(Split-Path $exePath -Leaf) yazilimi ile acilamayacak (kayit defterinden ayar silindi). [BASARILI]" -ForegroundColor Green
            }
            catch {
                Write-Host ""
                Write-Host "Islem basarisiz oldu: $_" -ForegroundColor Red
            }

            Write-Host ""
            $keepRunning = Wait-ForMenuReturn
        }

        "4" {
            Write-Host ""
            Write-Host "Betik Cikis secildi..."
            Write-Host ""
            $confirm = Read-Host "Cikmak istiyor musunuz? (E/H)"
            if ($confirm.ToUpper() -eq "E") {
                Write-Host ""
                Write-Host "Gule gule :) ...!"
                $keepRunning = $false
            }
            else {
                $keepRunning = $true
            }
        }

        default {
            Write-Host ""
            Write-Host "Gecersiz secim. Lutfen 1, 2, 3 veya 4 girin." -ForegroundColor Yellow
            Start-Sleep -Seconds 2
        }
    }
}

Read-Host "`nPress ENTER to exit."
Artık bundan sonra Güvenli Kip dahil, dosya uzantısı ilişkilendirme sorun olmaktan çıkmıştır.Güle güle kullanın...
Kullanıcı avatarı
TRWE_2012
Zettabyte1
Zettabyte1
Mesajlar: 15480
Kayıt: 25 Eyl 2013, 13:38
cinsiyet: Erkek
Teşekkür etti: 2653 kez
Teşekkür edildi: 5521 kez

Betiğin Saf İngiltere İngilizce Versiyonu

Mesaj gönderen TRWE_2012 »

file-association-manager.ps1

Kod: Tümünü seç

<#
    file-association-manager.ps1

    Purpose:
        Menu-driven file type association manager, generalising the classic
        "reg add / assoc / ftype" batch approach into a reusable PowerShell
        tool with three operations:
            1) Associate a file extension with a chosen program
            2) Reset a file extension's association back to a given default program
            3) Permanently remove a file extension's association from the registry
            4) Exit

    Registry locations touched (mirrors the original batch file's logic):
        HKEY_CLASSES_ROOT\Applications\<exeName>\shell\open\command
        HKEY_LOCAL_MACHINE\SOFTWARE\Classes\<progId>\DefaultIcon
        HKEY_LOCAL_MACHINE\SOFTWARE\Classes\<progId>\shell\open\command   (ftype equivalent)
        HKEY_CLASSES_ROOT\<extension>                                    (assoc equivalent)
        HKEY_CURRENT_USER\...\Explorer\FileExts\<extension>\Application
        HKEY_CURRENT_USER\...\Explorer\FileExts\<extension>\OpenWithList

    Known limitation (already observed by the user):
        Windows may accept this association change, but the Explorer icon
        shown for that file type can fail to refresh immediately. This is a
        long-standing Explorer icon cache behaviour, not something the
        registry writes below can fully control on their own.

    Double-click default note:
        Setting the registry keys above only makes the chosen program
        available in the "Open with" list; it does not by itself make
        Windows open that file type with it on double-click, because
        Windows protects the real default via a signed UserChoice hash.
        This script therefore also attempts to set the double-click default
        via the official DISM Import-DefaultAppAssociations mechanism. If
        that fails (a known limitation on some Windows builds), the user
        simply needs to pick the program once from the "How do you want to
        open this file?" dialog and select "Always".

    Requires: Administrator privileges. The script ALWAYS self-elevates to
              the highest available Administrator token before doing
              anything else, because HKEY_LOCAL_MACHINE and
              HKEY_CLASSES_ROOT writes, plus DISM, all require it.
#>

$ErrorActionPreference = "Stop"

# ---------------------------------------------------------------------------
# Always self-elevate to the highest Administrator privileges available,
# regardless of how the script was started.
# ---------------------------------------------------------------------------
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process powershell.exe -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "`"$PSCommandPath`"" -Verb RunAs
    exit
}

# Make sure the HKCR: PSDrive exists (not mounted by default in PowerShell)
if (-not (Get-PSDrive -Name HKCR -ErrorAction SilentlyContinue)) {
    New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT -ErrorAction SilentlyContinue | Out-Null
}

# ---------------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------------

function Get-NormalisedExtension {
    param([string]$Extension)
    $ext = $Extension.Trim()
    if (-not $ext.StartsWith(".")) {
        $ext = ".$ext"
    }
    return $ext.ToLower()
}

function Get-ProgIdForExtension {
    param([string]$Extension)
    $bare = $Extension.TrimStart(".")
    # Suffixed to avoid overwriting Windows' own built-in ProgIds
    # (e.g. plain "txtfile" or "htmlfile" already exist and are used by the OS).
    return "$($bare)file.Custom"
}

function Set-FileAssociation {
    param(
        [Parameter(Mandatory)][string]$Extension,
        [Parameter(Mandatory)][string]$ExecutablePath
    )

    $exeName = Split-Path -Path $ExecutablePath -Leaf
    $progId  = Get-ProgIdForExtension -Extension $Extension
    $openCommand = "`"$ExecutablePath`" `"%1`""

    # HKCR\Applications\<exeName>\shell\open\command
    $appCommandPath = "HKCR:\Applications\$exeName\shell\open\command"
    if (-not (Test-Path $appCommandPath)) {
        New-Item -Path $appCommandPath -Force | Out-Null
    }
    Set-Item -Path $appCommandPath -Value $openCommand

    # HKLM\SOFTWARE\Classes\<progId>\DefaultIcon
    $iconPath = "HKLM:\SOFTWARE\Classes\$progId\DefaultIcon"
    if (-not (Test-Path $iconPath)) {
        New-Item -Path $iconPath -Force | Out-Null
    }
    Set-Item -Path $iconPath -Value "$ExecutablePath,0"

    # HKLM\SOFTWARE\Classes\<progId>\shell\open\command  (ftype equivalent)
    $progCommandPath = "HKLM:\SOFTWARE\Classes\$progId\shell\open\command"
    if (-not (Test-Path $progCommandPath)) {
        New-Item -Path $progCommandPath -Force | Out-Null
    }
    Set-Item -Path $progCommandPath -Value $openCommand

    # HKCR\<extension>  (assoc equivalent: .ext -> progId)
    $extPath = "HKCR:\$Extension"
    if (-not (Test-Path $extPath)) {
        New-Item -Path $extPath -Force | Out-Null
    }
    Set-Item -Path $extPath -Value $progId

    # HKCU\...\Explorer\FileExts\<extension>\Application
    $fileExtsPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$Extension"
    if (-not (Test-Path $fileExtsPath)) {
        New-Item -Path $fileExtsPath -Force | Out-Null
    }
    Set-ItemProperty -Path $fileExtsPath -Name "Application" -Value $exeName

    # HKCU\...\Explorer\FileExts\<extension>\OpenWithList
    $openWithListPath = Join-Path $fileExtsPath "OpenWithList"
    if (-not (Test-Path $openWithListPath)) {
        New-Item -Path $openWithListPath -Force | Out-Null
    }
    Set-ItemProperty -Path $openWithListPath -Name "a" -Value $exeName
}

function Set-DefaultAppViaDism {
    param(
        [Parameter(Mandatory)][string]$Extension,
        [Parameter(Mandatory)][string]$ProgId,
        [Parameter(Mandatory)][string]$ApplicationName
    )

    $xmlPath = Join-Path $env:TEMP "defaultassoc_$([guid]::NewGuid().ToString('N')).xml"
    $xmlContent = @"
<?xml version="1.0" encoding="UTF-8"?>
<DefaultAssociations>
    <Association Identifier="$Extension" ProgId="$ProgId" ApplicationName="$ApplicationName" />
</DefaultAssociations>
"@
    Set-Content -Path $xmlPath -Value $xmlContent -Encoding UTF8

    try {
        $output = & dism.exe /Online /Import-DefaultAppAssociations:"$xmlPath" 2>&1
        $exitCode = $LASTEXITCODE
        return [PSCustomObject]@{
            Success  = ($exitCode -eq 0)
            ExitCode = $exitCode
            Output   = ($output | Out-String)
        }
    }
    catch {
        return [PSCustomObject]@{
            Success  = $false
            ExitCode = -1
            Output   = "$_"
        }
    }
    finally {
        Remove-Item -Path $xmlPath -Force -ErrorAction SilentlyContinue
    }
}

function Remove-FileAssociation {
    param(
        [Parameter(Mandatory)][string]$Extension,
        [Parameter(Mandatory)][string]$ExecutablePath
    )

    $exeName = Split-Path -Path $ExecutablePath -Leaf
    $progId  = Get-ProgIdForExtension -Extension $Extension

    $pathsToRemove = @(
        "HKCR:\Applications\$exeName",
        "HKLM:\SOFTWARE\Classes\$progId",
        "HKCR:\$Extension",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$Extension"
    )

    foreach ($path in $pathsToRemove) {
        if (Test-Path $path) {
            Remove-Item -Path $path -Recurse -Force -ErrorAction SilentlyContinue
        }
    }
}

function Show-Menu {
    Write-Host "==================================================================================================="
    Write-Host "Welcome to the File Format - Software File Association Manager."
    Write-Host "==================================================================================================="
    Write-Host ""
    Write-Host "What would you like to do...?!"
    Write-Host ""
    Write-Host "1 = Associate a File Format with Software"
    Write-Host "2 = Reset a File Format - Software Association back to Default"
    Write-Host "3 = Permanently Delete a File Format - Software Association from the Registry"
    Write-Host "4 = Exit Script"
    Write-Host ""
}

function Wait-ForMenuReturn {
    while ($true) {
        $choice = Read-Host "Press R to return to the Main Menu, or E to exit the script, then press Enter"
        switch ($choice.ToUpper()) {
            "R" { return $true }
            "E" { return $false }
            default { Write-Host "Invalid choice, please enter R or E." -ForegroundColor Yellow }
        }
    }
}

# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------

$keepRunning = $true

while ($keepRunning) {
    Clear-Host
    Show-Menu

    $selection = Read-Host "Please enter your choice and press Enter"

    switch ($selection) {
        "1" {
            Write-Host ""
            Write-Host "Associate a File Format with Software selected..."
            Write-Host ""
            $ext = Read-Host "Enter the file extension"
            $ext = Get-NormalisedExtension -Extension $ext
            $exePath = Read-Host "Enter the full path of the software to associate"

            if (-not (Test-Path $exePath)) {
                Write-Host ""
                Write-Host "WARNING: the specified path was not found, continuing anyway." -ForegroundColor Yellow
            }

            try {
                Set-FileAssociation -Extension $ext -ExecutablePath $exePath
                Write-Host ""
                Write-Host "Association of the $ext file format with $(Split-Path $exePath -Leaf)... [SUCCESSFUL]" -ForegroundColor Green

                $progId = Get-ProgIdForExtension -Extension $ext
                $appName = [System.IO.Path]::GetFileNameWithoutExtension($exePath)
                Write-Host ""
                Write-Host "Attempting to set the double-click default via DISM..."
                $dismResult = Set-DefaultAppViaDism -Extension $ext -ProgId $progId -ApplicationName $appName
                if ($dismResult.Success) {
                    Write-Host "The default application was set successfully via DISM. The 'How do you want to open this?' prompt should no longer appear." -ForegroundColor Green
                }
                else {
                    Write-Host "Automatic assignment via DISM failed (exit code: $($dismResult.ExitCode))." -ForegroundColor Yellow
                    Write-Host "This is a known Windows limitation. Fix: the next time you double-click a matching file," -ForegroundColor Yellow
                    Write-Host "select $appName in the dialog and click 'Always'." -ForegroundColor Yellow
                }
            }
            catch {
                Write-Host ""
                Write-Host "The operation failed: $_" -ForegroundColor Red
            }

            Write-Host ""
            $keepRunning = Wait-ForMenuReturn
        }

        "2" {
            Write-Host ""
            Write-Host "Reset a File Format - Software Association back to Default selected."
            Write-Host ""
            $ext = Read-Host "Enter the file extension"
            $ext = Get-NormalisedExtension -Extension $ext
            $exePath = Read-Host "Enter the full path of the default software to associate"

            if (-not (Test-Path $exePath)) {
                Write-Host ""
                Write-Host "WARNING: the specified path was not found, continuing anyway." -ForegroundColor Yellow
            }

            try {
                Set-FileAssociation -Extension $ext -ExecutablePath $exePath
                Write-Host ""
                Write-Host "The $ext file format has been reset to open with the default software. [SUCCESSFUL]" -ForegroundColor Green

                $progId = Get-ProgIdForExtension -Extension $ext
                $appName = [System.IO.Path]::GetFileNameWithoutExtension($exePath)
                Write-Host ""
                Write-Host "Attempting to set the double-click default via DISM..."
                $dismResult = Set-DefaultAppViaDism -Extension $ext -ProgId $progId -ApplicationName $appName
                if ($dismResult.Success) {
                    Write-Host "The default application was set successfully via DISM. The 'How do you want to open this?' prompt should no longer appear." -ForegroundColor Green
                }
                else {
                    Write-Host "Automatic assignment via DISM failed (exit code: $($dismResult.ExitCode))." -ForegroundColor Yellow
                    Write-Host "This is a known Windows limitation. Fix: the next time you double-click a matching file," -ForegroundColor Yellow
                    Write-Host "select $appName in the dialog and click 'Always'." -ForegroundColor Yellow
                }
            }
            catch {
                Write-Host ""
                Write-Host "The operation failed: $_" -ForegroundColor Red
            }

            Write-Host ""
            $keepRunning = Wait-ForMenuReturn
        }

        "3" {
            Write-Host ""
            Write-Host "Permanently Delete a File Format - Software Association from the Registry [WARNING..!]" -ForegroundColor Yellow
            Write-Host ""
            $ext = Read-Host "Enter the file extension"
            $ext = Get-NormalisedExtension -Extension $ext
            $exePath = Read-Host "Enter the full path of the software to associate"

            try {
                Remove-FileAssociation -Extension $ext -ExecutablePath $exePath
                Write-Host ""
                Write-Host "The $ext file format can no longer be opened with $(Split-Path $exePath -Leaf) (the registry setting has been removed). [SUCCESSFUL]" -ForegroundColor Green
            }
            catch {
                Write-Host ""
                Write-Host "The operation failed: $_" -ForegroundColor Red
            }

            Write-Host ""
            $keepRunning = Wait-ForMenuReturn
        }

        "4" {
            Write-Host ""
            Write-Host "Exit Script selected..."
            Write-Host ""
            $confirm = Read-Host "Do you want to exit? (Y/N)"
            if ($confirm.ToUpper() -eq "Y") {
                Write-Host ""
                Write-Host "Goodbye :) ...!"
                $keepRunning = $false
            }
            else {
                $keepRunning = $true
            }
        }

        default {
            Write-Host ""
            Write-Host "Invalid choice. Please enter 1, 2, 3 or 4." -ForegroundColor Yellow
            Start-Sleep -Seconds 2
        }
    }
}

Read-Host "`nPress ENTER to exit."
Ekran Görüntüsü :
Resim
Güle güle kullanın...
Kullanıcı avatarı
burak35
Zettabyte3
Zettabyte3
Mesajlar: 17924
Kayıt: 07 Eki 2016, 13:06
cinsiyet: Erkek
Teşekkür etti: 10362 kez
Teşekkür edildi: 12121 kez

Re: Dosya İlişkilendirme PS1 Betiği

Mesaj gönderen burak35 »

olabildiğince elle ayarlıyorum. sanırım çok titizim.
Cevapla

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