$wallpaperUrl = "https://www.pajcomp.pl/pub/%21Misc/Marketing/Tapety/Tapeta_2024_fhd.png"
$wallpaperPath = Join-Path "$env:USERPROFILE\Pictures\" (Split-Path $wallpaperUrl -Leaf)


$LogFileGlobal = "C:\Serwis\czyszczenie_windows.log"
if (-not (Test-Path "C:\Serwis")) {
    New-Item -ItemType Directory -Path "C:\Serwis" | Out-Null
}

# Remedium na wolne pobieranie plikw z internetu
$ProgressPreference = 'SilentlyContinue'

function Start-Main {

    try {
        Write-Host "Pobieranie obrazu z $wallpaperUrl..." -ForegroundColor Yellow
        Invoke-WebRequest -Uri $wallpaperUrl -OutFile $wallpaperPath -ErrorAction Stop
    }
    catch {
        Show-Except
    }

    Write-Host "Czy chcesz zastosowa ustawienia tylko dla biecego konta uytkownika czy dla caego komputera?" -ForegroundColor Yellow
    Write-Host "1. Dla caego komputera [Domylna warto]"
    Write-Host "2. Tylko dla biecego konta uytkownika"
    Write-Host "3. Dodaj administratora i zmie obecnego uytkownika na zwykego"
    $choice = Read-Host "Wybierz opcj (1/2/3)"

    switch ($choice) {
        "2" {
            Write-HostAndLog "Tylko dla biecego konta uytkownika ..."
            Remove-Apps
            NewsInterests -Disable
            Fix-Registry-User
            Fix-Registry-Computer
        }
        "3" {
            Write-HostAndLog "Dodaj administratora i zmie obecnego uytkownika na zwykego ..."
            Add-Admin
        }
        default {
            Write-HostAndLog "Zastosowanie ustawie tylko dla caego komputera ..."
            Disable-Services
            Remove-Apps
            NewsInterests -Disable
            Fix-Registry-User
            Write-Host "Czyszczenie uzytkownika zakoczone!" -ForegroundColor Yellow -BackgroundColor Green
            Fix-Registry-Computer
            Write-Host "Koniec komputera!" -ForegroundColor Yellow -BackgroundColor Green
            
            Write-Host "Czy doda konto admina a obecnego uytkownika zrobi zwyklym?" -ForegroundColor Yellow
            Write-Host "1. TAK - dodaj admina [Domylna warto]"
            Write-Host "2. Nie"
            $choice2 = Read-Host "Wybierz opcj (1/2)"
        
            switch ($choice2) {
                "2" {
                    Write-HostAndLog "Nie nie robimy ..."
                }
                default {
                    Write-HostAndLog "Dodany zostanie nowy administrator ..."
                    Add-Admin
                }
            }


        }
    }
    Write-Host "Czyszczenie systemu Windows zakoczone!" -ForegroundColor Yellow -BackgroundColor Green
    Clean-Disk
    End-Main
}

<#
Ponizej znajduja sie funkcje pomocnicze, ktore sa wykorzystywane w skrypcie.
A na koncu wywolanie glownej funkcji skryptu.
#>

function Write-Log { 
    param (
        [Parameter(Mandatory = $true)]
        [string]$Message,
        
        [string]$LogFile = 
        $(if ($LogFile) { 
                $LogFile 
            }
            elseif ($LogFileGlobal) { 
                $LogFileGlobal
            }
            else { 
                "$([System.IO.Path]::GetFileNameWithoutExtension($PSCommandPath)).log"
            })
    )

    $Stamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
    $LogMessage = "$Stamp $Message"
    
    try {
        Add-Content -Path $LogFile -Value $LogMessage -Encoding UTF8 -ErrorAction Stop
    }
    catch {
        Write-Host "===================================="
        Write-Host "  Nie mozna zapisa do pliku logu: $LogFile"
        Write-Host "  Blad: $_"
        Write-Host "===================================="
    }
}

# Funkcja wywietla w konsoli informacje i zapisuje ja do pliku logu
function Write-HostAndLog { 
    param (
        [Parameter(Mandatory = $true)]
        [string]$Message,
        
        [string]$LogFile = 
        $(if ($LogFile) { 
                $LogFile 
            }
            elseif ($LogFileGlobal) { 
                $LogFileGlobal
            }
            else { 
                "$([System.IO.Path]::GetFileNameWithoutExtension($PSCommandPath)).log"
            })
    )
    
    Write-Host $Message
    Write-Log -Message $Message -LogFile $LogFile
}

# Funkcja do obslugi wyjatkow
# Wywietla uzytkownikowi opis problemu i zapisuje go w pliku logu
function Show-Except {

    $errorDetails = $_
    $errorMessage = @"
==================================================
  Wystapil blad!
  Lokalizacja: $($errorDetails.InvocationInfo.ScriptName)
  Linia: $($errorDetails.InvocationInfo.ScriptLineNumber)
  Blad: $($errorDetails.Exception.Message)
  Szczegoly: $($errorDetails.ScriptStackTrace)
==================================================
"@

    Write-HostAndLog $errorMessage
}

function  Disable-Services {
   
    Write-HostAndLog "Wyczanie zbdnych usug systemowych..." 

    # Lista usug do wyczenia
    $servicesToDisable = @(
        "AJRouter", # AllJoyn Router Service (zbdne dla wikszoci uytkownikw)
        "DiagTrack", # Connected User Experiences and Telemetry
        "diagnosticshub.standardcollector.service", # Diagnostics Hub Standard Collector
        "dmwappushservice", # WAP Push Message Routing Service
        "DusmSvc", # Data Usage Service 
        "DoSvc", # Delivery Optimization (optymalizacja pobierania aktualizacji, mona wyczy, jeli nie korzystasz z P2P aktualizacji)
        "DPS", # Diagnostic Policy Service
        "EdgeElevationService", # Microsoft Edge Elevation Service
        "EdgeUpdate", # Microsoft Edge Update Service (jeli nie chcesz automatycznych aktualizacji Edge)
        "Fax", # Fax Service
        "iphlpsvc", # IP Helper (obsuguje IPv6, mona wyczy, jeli uywasz tylko IPv4)
        "lfsvc", # Geolocation Service
        "MapsBroker", # Downloaded Maps Manager
        "MessagingService", # Messaging Service
        "NetTcpPortSharing", # Net.Tcp Port Sharing Service
        "PcaSvc", # Program Compatibility Assistant Service
        "PhoneSvc", # Phone Service
        "RemoteRegistry", # Remote Registry
        "RetailDemo", # Retail Demo Service
        "SEMgrSvc", # Payments and NFC/SE Manager
        "SharedAccess", # Internet Connection Sharing (ICS)
        "stisvc", # Windows Image Acquisition (jeli nie uywasz skanerw i aparatw)
        "SysMain", # Superfetch (mona wyczy, jeli nie korzystasz z dysku SSD)
        #   "TabletInputService",        # Touch Keyboard and Handwriting Panel Service (jeli nie uywasz ekranu dotykowego)
        "TrkWks", # Distributed Link Tracking Client (zbdne dla wikszoci uytkownikw)
        "WbioSrvc", # Windows Biometric Service
        "WerSvc", # Windows Error Reporting Service
        "WMPNetworkSvc", # Windows Media Player Network Sharing Service
        "WSearch", # Windows Search (jeli nie uywasz wyszukiwania)
        "XblAuthManager", # Xbox Live Auth Manager
        "XblGameSave", # Xbox Live Game Save
        "XboxNetApiSvc"              # Xbox Live Networking Service
    )

    # Wyczanie usug
    foreach ($service in $servicesToDisable) {
        Write-HostAndLog "Wyczanie usugi: $service"

        # Sprawdzenie, czy usuga istnieje
        $svc = Get-Service -Name $service -ErrorAction SilentlyContinue
        if ($svc) {
            try {
                # Wyczenie usugi i zatrzymanie jej
                Set-Service -Name $service -StartupType Disabled -ErrorAction Stop
                if ($svc.Status -ne "Stopped") {
                    Stop-Service -Name $service -Force -ErrorAction Stop
                }
                Write-HostAndLog "Usuga $service zostaa wyczona i zatrzymana."
            }
            catch {
                Write-HostAndLog "Bd podczas wyczania usugi $service $_"
                Show-Except
            }
        }
        else {
            Write-HostAndLog "Usuga $service nie zostaa znaleziona."
        }
    }
    Write-HostAndLog "Wybrane usugi zostay wyczone."
}


## Przewracanie usunietej aplikacji:
# Get-AppxPackage -AllUsers *Microsoft.StorePurchaseApp* | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppXManifest.xml"}

function Remove-Apps {

    Write-HostAndLog "Usuwanie zbdnych aplikacji systemowych..."

    # Lista aplikacji do usunicia
    $appsToRemove = @(
        "Microsoft.Microsoft3DViewer",
        "Microsoft.AppConnector",
        "Microsoft.BingFinance",
        "Microsoft.BingNews",
        "Microsoft.BingSports",
        "Microsoft.BingTranslator",
        "Microsoft.BingWeather",
        "Microsoft.BingFoodAndDrink",
        "Microsoft.BingHealthAndFitness",
        "Microsoft.BingTravel",
        "Microsoft.MinecraftUWP",
        "Microsoft.GamingServices",
        "Microsoft.GamingApp",
        "Microsoft.GetHelp",
        "Microsoft.Getstarted",
        "Microsoft.Messaging",
        "Microsoft.MicrosoftSolitaireCollection",
        "Microsoft.NetworkSpeedTest",
        "Microsoft.News",
        "Microsoft.Office.Lens",
        "Microsoft.Office.Sway",
        "Microsoft.Office.OneNote",
        "Microsoft.OneConnect",
        "Microsoft.People",
        "Microsoft.Print3D",
        "Microsoft.SkypeApp",
        "Microsoft.Wallet",
        "Microsoft.Whiteboard",
        "Microsoft.WindowsAlarms",
        "microsoft.windowscommunicationsapps",
        "Microsoft.Windows.DevHome",
        "Microsoft.WindowsFeedbackHub",
        "Microsoft.WindowsMaps",
        "Microsoft.YourPhone",
        "Microsoft.WindowsSoundRecorder",
        "Microsoft.XboxApp",
        "Microsoft.ConnectivityStore",
        "Microsoft.ScreenSketch",
        "Microsoft.Xbox.TCUI",
        "Microsoft.XboxGameOverlay",
        "Microsoft.XboxGameCallableUI",
        "Microsoft.XboxSpeechToTextOverlay",
        "Microsoft.MixedReality.Portal",
        "Microsoft.XboxIdentityProvider",
        "Microsoft.ZuneMusic",
        "Microsoft.ZuneVideo",
        "Microsoft.MicrosoftOfficeHub",
        "*EclipseManager*",
        "*ActiproSoftwareLLC*",
        "*AdobeSystemsIncorporated.AdobePhotoshopExpress*",
        "*Duolingo-LearnLanguagesforFree*",
        "*PandoraMediaInc*",
        "*CandyCrush*",
        "*BubbleWitch3Saga*",
        "*Wunderlist*",
        "*Flipboard*",
        "*Twitter*",
        "*Facebook*",
        "*Royal Revolt*",
        "*Sway*",
        "*Speed Test*",
        "*Dolby*",
        "*Viber*",
        "*ACGMediaPlayer*",
        "*Netflix*",
        "*OneCalendar*",
        "*LinkedInforWindows*",
        "*HiddenCityMysteryofShadows*",
        "*Hulu*",
        "*HiddenCity*",
        "*AdobePhotoshopExpress*",
        "*HotspotShieldFreeVPN*",
        "*Microsoft.Advertising.Xaml*",
        "*Sticky*",
        "*xbox*",
        "*copilot*",
        "*clipchamp*",
        "*todos*",
        "*windowscamera*",
        "*PowerAutomate*",
        "*QuickAssist*",
        "*OutlookForWindows*",   
        "*Microsoft.Windows.Photos*",
        "*BingSearch*",
        "Microsoft.3DBuilder",
        "Microsoft.MSPaint",
        "Microsoft.StorePurchaseApp",
        "Microsoft.XboxGamingOverlay",
        "Microsoft.StartExperiencesApp",
        "MicrosoftFamily",
        "*Teams*",
        "Microsoft.549981C3F5F10"
    )

    # Usuwanie aplikacji
    foreach ($app in $appsToRemove) {
        Write-HostAndLog "Usuwanie $app..."

        # Sprawdzenie i usunicie pakietu dla biecego uytkownika
        $package = Get-AppxPackage -Name $app -ErrorAction SilentlyContinue
        if ($package) {
            try {
                Remove-AppxPackage -Package $package.PackageFullName -ErrorAction Stop
                Write-HostAndLog "Usunito $app dla biecego uytkownika."
            }
            catch {
                Write-HostAndLog "Bd usuwania $app dla biecego uytkownika: $_"
                Show-Except
            }
        }

        # Sprawdzenie i usunicie pakietu dla wszystkich uytkownikw (wymaga uprawnie Administratora)
        $packageAllUsers = Get-AppxPackage -Name $app -AllUsers -ErrorAction SilentlyContinue
        if ($packageAllUsers) {
            try {
                Remove-AppxPackage -Package $packageAllUsers.PackageFullName -AllUsers -ErrorAction Stop
                Write-HostAndLog "Usunito $app dla wszystkich uytkownikw."
            }
            catch {
                Write-HostAndLog "Bd usuwania $app dla wszystkich uytkownikw: $_"
                Show-Except
            }
        }

        # Usunicie prowizji pakietu (dla aplikacji systemowych)
        $provisioned = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $app } -ErrorAction SilentlyContinue
        if ($provisioned) {
            try {
                Remove-AppxProvisionedPackage -Online -PackageName $provisioned.PackageName -ErrorAction Stop
                Write-HostAndLog "Usunito prowizj pakietu $app."
            }
            catch {
                Write-HostAndLog "Bd usuwania prowizji $app $_"
                Show-Except
            }
        }

        if (-not $package -and -not $packageAllUsers -and -not $provisioned) {
            Write-HostAndLog "Pakiet $app nie zosta znaleziony."
        }
    }

    Write-HostAndLog "Usuwanie Microsoft Teams..."

    $TeamsPath = [System.IO.Path]::Combine($env:LOCALAPPDATA, 'Microsoft', 'Teams')
    $TeamsUpdateExePath = [System.IO.Path]::Combine($TeamsPath, 'Update.exe')

    Write-HostAndLog "Zatrzymywanie procesu Teams..."
    Stop-Process -Name "*teams*" -Force -ErrorAction SilentlyContinue

    Write-HostAndLog "Odinstalowywanie Teams z AppData\Microsoft\Teams"
    if ([System.IO.File]::Exists($TeamsUpdateExePath)) {
        $proc = Start-Process $TeamsUpdateExePath "-uninstall -s" -PassThru
        $proc.WaitForExit()
    }

    Write-HostAndLog "Usuwanie katalogu Teams"
    if ([System.IO.Directory]::Exists($TeamsPath)) {
        Remove-Item $TeamsPath -Force -Recurse -ErrorAction SilentlyContinue
    }

    Write-HostAndLog "Usuwanie klucza rejestru odinstalowania Teams"
    $us = (Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | 
        Get-ItemProperty | Where-Object { $_.DisplayName -like '*Teams*' }).UninstallString

    if ($us.Length -gt 0) {
        $us = ($us.Replace('/I', '/uninstall ') + ' /quiet').Replace('  ', ' ')
        $FilePath = ($us.Substring(0, $us.IndexOf('.exe') + 4).Trim())
        $ProcessArgs = ($us.Substring($us.IndexOf('.exe') + 5).Trim().replace('  ', ' '))
        $proc = Start-Process -FilePath $FilePath -Args $ProcessArgs -PassThru
        $proc.WaitForExit()
    }

    Write-HostAndLog "Proces usuwania Teams zakoczony!"

    # Informacja o usuwaniu OneDrive
    Write-HostAndLog "Usuwanie OneDrive..."

    # Usunicie OneDrive
    taskkill /F /IM OneDrive.exe
    if (Test-Path "C:\Windows\System32\OneDriveSetup.exe") {
        Write-HostAndLog "Uninstalling OneDrive from System32..."
        Start-Process -FilePath "C:\Windows\System32\OneDriveSetup.exe" -ArgumentList "/uninstall" -Wait -NoNewWindow
    }

    if (Test-Path "C:\Windows\SysWOW64\OneDriveSetup.exe") {
        Write-HostAndLog "Uninstalling OneDrive from SysWOW64..."
        Start-Process -FilePath "C:\Windows\SysWOW64\OneDriveSetup.exe" -ArgumentList "/uninstall" -Wait -NoNewWindow
    }

    Remove-Item -Path "$env:USERPROFILE\OneDrive" -Force -Recurse -ErrorAction SilentlyContinue
    Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\OneDrive" -Force -Recurse -ErrorAction SilentlyContinue
    Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\OneDrive" -Name "DisableFileSyncNGSC" -Value 1 -Type DWord -Force


    Write-HostAndLog "Hide first sign-in animation after the upgrade"
    New-ItemProperty -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer -Name HideRecommendedSection -PropertyType DWord -Value 1 -Force
    Set-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer" -Name "HideRecommendedSection" -Value 1 -Type DWord


}

function Fix-Registry-User {
    # ------------------------------------------------------
    Write-HostAndLog "Change the feedback frequency to Never"
    if (-not (Test-Path -Path HKCU:\Software\Microsoft\Siuf\Rules)) {
        New-Item -Path HKCU:\Software\Microsoft\Siuf\Rules -Force
    }
    New-ItemProperty -Path HKCU:\Software\Microsoft\Siuf\Rules -Name NumberOfSIUFInPeriod -PropertyType DWord -Value 0 -Force
    Remove-ItemProperty -Path HKCU:\Software\Microsoft\Siuf\Rules -Name PeriodInNanoSeconds -Force -ErrorAction Ignore

    # ------------------------------------------------------
    Write-HostAndLog "Wyczanie spersonalizowanych reklam i sugestii..."
    New-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name HttpAcceptLanguageOptOut -PropertyType DWord -Value 1 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Do not let apps show me personalized ads by using my advertising ID"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo -Name Enabled -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Hide the Windows welcome experiences after updates and occasionally when I sign in to highlight what's new and suggested"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-310093Enabled -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Do not get tips and suggestions when I use Windows"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338389Enabled -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Hide from me suggested content in the Settings app"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338393Enabled -PropertyType DWord -Value 0 -Force
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353694Enabled -PropertyType DWord -Value 0 -Force
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353696Enabled -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Turn off automatic installing suggested apps"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SilentInstalledAppsEnabled -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Do not suggest ways to get the most out of Windows and finish setting up this device"
    if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\UserProfileEngagement)) {
        New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Force
    }
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Name ScoobeSystemSettingEnabled -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Don't let Microsoft use your diagnostic data for personalized tips, ads, and recommendations"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Privacy -Name TailoredExperiencesWithDiagnosticDataEnabled -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Disable Bing search in Start Menu"
    if (-not (Test-Path -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer)) {
        New-Item -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer -Force
    }
    New-ItemProperty -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer -Name DisableSearchBoxSuggestions -PropertyType DWord -Value 1 -Force
    Set-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer" -Name "DisableSearchBoxSuggestions" -Value 1 -Type DWord

    # ------------------------------------------------------
    Write-HostAndLog "Do not show recommendations for tips, shortcuts, new apps, and more in Start menu"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Start_IrisRecommendations -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Do not show Microsoft account-related notifications on Start Menu in Start menu"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Start_AccountNotifications -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Hide the "This PC" icon on Desktop (default value)"
    Remove-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -Force -ErrorAction Ignore

    # ------------------------------------------------------
    Write-HostAndLog "Ukrywanie ikon i skrtw na pulpicie..."
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" -Name "{645FF040-5081-101B-9F08-00AA002F954E}" -Value 1

    # ------------------------------------------------------
    Write-HostAndLog "Usuwanie skrtw z pulpitu uytkownika"
    Get-ChildItem -Path "$([Environment]::GetFolderPath('DesktopDirectory'))" -Filter "*.lnk" | Remove-Item -Force -ErrorAction SilentlyContinue

    # ------------------------------------------------------
    Write-HostAndLog "Show hidden files, folders, and drives"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Hidden -PropertyType DWord -Value 1 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Show file name extensions"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Open File Explorer to This PC"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -PropertyType DWord -Value 1 -Force
    
    # ------------------------------------------------------
    Write-HostAndLog "When I snap a window, do not show what I can snap next to it"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SnapAssist -PropertyType DWord -Value 0 -Force
    
    # ------------------------------------------------------
    Write-HostAndLog "Show the file transfer dialog box in the detailed mode"
    if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager)) {
        New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager -Force
    }
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager -Name EnthusiastMode -PropertyType DWord -Value 1 -Force
    
    # ------------------------------------------------------
    Write-HostAndLog "Hide recently used files in Quick access"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer -Name ShowRecent -PropertyType DWord -Value 0 -Force
    
    # ------------------------------------------------------
    Write-HostAndLog "Hide frequently used folders in Quick access"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer -Name ShowFrequent -PropertyType DWord -Value 0 -Force
    
    # ------------------------------------------------------
    Write-HostAndLog "Set the taskbar alignment to the left"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name TaskbarAl -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Hide the Meet Now icon in the notification area"
    $Script:MeetNow = $false
    $Settings = Get-ItemPropertyValue -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3 -Name Settings -ErrorAction Ignore
    $Settings[9] = 128
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3 -Name Settings -PropertyType Binary -Value $Settings -Force

    # ------------------------------------------------------
    Write-HostAndLog "Always show all icons in the notification area"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer -Name EnableAutoTray -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Hide the search on the taskbar"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Search -Name SearchboxTaskbarMode -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Hide the Task view button from the taskbar"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowTaskViewButton -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Usuwanie przypitych aplikacji z paska zada..."
    Write-HostAndLog "Usuwanie wszystkich skrtw z folderu przypitych aplikacji"
    $taskbarPath = "$env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar"
    if (Test-Path $taskbarPath) {
        Remove-Item -Path "$taskbarPath\*" -Force -Recurse -ErrorAction SilentlyContinue
        Write-HostAndLog "Usunito skrty z folderu TaskBar."
    }

    Write-HostAndLog "Czyszczenie kluczy rejestru zwizanych z paskiem zada"
    $registryKeys = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband"
    )
    foreach ($key in $registryKeys) {
        if (Test-Path $key) {
            Remove-Item -Path $key -Recurse -Force -ErrorAction SilentlyContinue
            Write-HostAndLog "Usunito klucz rejestru: $key"
        }
    }

    
    Write-HostAndLog "Hide the widgets icon on the taskbar"
    # We cannot set a value to TaskbarDa, having called any of APIs, except of copying powershell.exe (or any other tricks) with a different name, due to a UCPD driver tracks all executables to block the access to the registry
    Copy-Item -Path "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -Destination "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Force
    & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Command { New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name TaskbarDa -PropertyType DWord -Value 0 -Force }


    # ------------------------------------------------------
    Write-HostAndLog "Set the default Windows mode to dark"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name SystemUsesLightTheme -PropertyType DWord -Value 0 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Set the default app mode to light (default value)"
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -PropertyType DWord -Value 1 -Force
   
    # ------------------------------------------------------
    Write-HostAndLog "Do not add the - Shortcut suffix to the file name of created shortcuts"
    if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates)) {
        New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates -Force
    }
    New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates -Name ShortcutNameTemplate -PropertyType String -Value "%s.lnk" -Force

    # ------------------------------------------------------
    Write-HostAndLog "Do not group files and folder in the Downloads folder"
    Get-ChildItem -Path "HKCU:\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\*\Shell" -Recurse | Where-Object -FilterScript { $_.PSChildName -eq "{885A186E-A440-4ADA-812B-DB871B942259}" } | Remove-Item -Force

    # https://learn.microsoft.com/en-us/windows/win32/properties/props-system-null
    if (-not (Test-Path -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}")) {
        New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Force
    }
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Name ColumnList -PropertyType String -Value "System.Null" -Force
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Name GroupBy -PropertyType String -Value "System.Null" -Force
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Name LogicalViewMode -PropertyType DWord -Value 1 -Force
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Name Name -PropertyType String -Value NoName -Force
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Name Order -PropertyType DWord -Value 0 -Force
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Name PrimaryProperty -PropertyType String -Value "System.ItemNameDisplay" -Force
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FolderTypes\{885a186e-a440-4ada-812b-db871b942259}\TopViews\{00000000-0000-0000-0000-000000000000}" -Name SortByList -PropertyType String -Value "prop:System.ItemNameDisplay" -Force

    # ------------------------------------------------------
    Write-HostAndLog "Remove Recommended section in Start Menu. Not applicable to Home edition"
    if (-not (Test-Path -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer)) {
        New-Item -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer -Force
    }
    
    # -----------------------------------------------------------
    Write-HostAndLog "Disable Windows Script Host. Blocks WSH from executing .js and .vbs files"
    if (-not (Test-Path -Path "HKCU:\Software\Microsoft\Windows Script Host\Settings")) {
        New-Item -Path "HKCU:\Software\Microsoft\Windows Script Host\Settings" -Force
    }
    New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows Script Host\Settings" -Name Enabled -PropertyType DWord -Value 0 -Force

    # -------------------------------------------------------------
    Write-HostAndLog "Przywracanie klasycznego menu kontekstowego..."
    New-Item -Path "HKCU:\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" -Force
    New-Item -Path "HKCU:\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" -Force -ErrorAction Stop | Out-Null
    Set-ItemProperty -Path "HKCU:\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" -Name "(Default)" -Value "" -Force -ErrorAction Stop

    # ----------------------------------------------------------------
    Write-HostAndLog "Wyczanie funkcji Timeline..."
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Privacy" -Name "ActivityHistoryEnabled" -Value 0 -Force

    Write-HostAndLog "Ustawianie tapety na ekranie blokady i pulpitu..."


    # Ustawienie ta pulpitu
    try {
        Write-HostAndLog "Ustawianie ta pulpitu..."
        Add-Type -TypeDefinition @"
        using System;
        using System.Runtime.InteropServices;
        public class Wallpaper {
            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
        }
"@ -Language CSharp
        
        $SPI_SETDESKWALLPAPER = 20
        $SPIF_UPDATEINIFILE = 1
        $SPIF_SENDCHANGE = 2
        
        [Wallpaper]::SystemParametersInfo($SPI_SETDESKWALLPAPER, 0, $wallpaperPath, $SPIF_UPDATEINIFILE -bor $SPIF_SENDCHANGE) | Out-Null
        
        RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters , 1 , True
    }
    catch {
        Show-Except
    }
    
    Write-HostAndLog "Ustawianie ta pulpitu..."
    Set-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name "Wallpaper" -Value $wallpaperPath
    
    Write-HostAndLog "Ustawienia dla Windows Spotlight (wyczenie)"
    $regPath1 = "HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager"
    Set-ItemProperty -Path $regPath1 -Name "RotatingLockScreenEnabled" -Value 0 -ErrorAction SilentlyContinue
    Set-ItemProperty -Path $regPath1 -Name "RotatingLockScreenOverlayEnabled" -Value 0 -ErrorAction SilentlyContinue

    Write-HostAndLog "Wycz Game DVR i funkcje nagrywania"
    $regPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\GameDVR"
    if (-not (Test-Path $regPath)) { New-Item -Path $regPath -Force | Out-Null }
    Set-ItemProperty -Path $regPath -Name "AppCaptureEnabled" -Value 0
    Set-ItemProperty -Path $regPath -Name "GameDVREnabled" -Value 0

    Write-HostAndLog "Wyczanie trybu gry..."
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\GameBar" -Name "AllowAutoGameMode" -Value 0 -Force

    Write-HostAndLog "Wycz Windows Spotlight"
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" -Name "RotatingLockScreenEnabled" -Value 0
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" -Name "RotatingLockScreenOverlayEnabled" -Value 0



}

function Fix-Registry-Computer {
    # ------------------------------------------------------
    Write-HostAndLog "Set the diagnostic data collection to minimum"
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name "AllowTelemetry" -Value 0

    # ------------------------------------------------------
    Write-HostAndLog "Turn off the Windows Error Reporting"
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" -Name "Disabled" -Value 1

    # ------------------------------------------------------
    Write-HostAndLog "Wyczanie automatycznego logowania po aktualizacji..."
    Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name DisableAutomaticRestartSignOn -Force -ErrorAction Ignore
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "DisableAutomaticRestartSignOn" -Value 1
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "DoNotUseSignInInfoToFinishSetupAfterUpdate" -Value 1
    
    $SID = (Get-CimInstance -ClassName Win32_UserAccount | Where-Object -FilterScript { $_.Name -eq $env:USERNAME }).SID
    if (-not (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\UserARSO\$SID")) {
        New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\UserARSO\$SID" -Force
    }
    New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\UserARSO\$SID" -Name OptOut -PropertyType DWord -Value 1 -Force

    # ------------------------------------------------------
    Write-HostAndLog "Removes the Home and Gallery from explorer"
    Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\{e88865ea-0e1c-4e20-9aa6-edcd0212c87c}" -Force -Recurse -ErrorAction SilentlyContinue
    Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\{f874310e-b6b7-47dc-bc84-b9e6b38f5903}" -Force -Recurse -ErrorAction SilentlyContinue

    # ------------------------------------------------------
    Write-HostAndLog "Usuwanie skrtw z pulpitu wsplnego"
    Get-ChildItem -Path "$([Environment]::GetFolderPath('CommonDesktopDirectory'))" -Filter "*.lnk" | Remove-Item -Force -ErrorAction SilentlyContinue
    
    # ------------------------------------------------------
    Write-HostAndLog "Wyczanie zada diagnostycznych w harmonogramie..."
    Get-ScheduledTask | Where-Object { $_.TaskName -match "DiagTrack|DmClient" } | ForEach-Object { Disable-ScheduledTask -TaskName $_.TaskName -TaskPath $_.TaskPath }

    # ---------------------------------------------------------
    Write-HostAndLog "Hide first sign-in animation after the upgrade"
    New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name EnableFirstLogonAnimation -PropertyType DWord -Value 0 -Force

    if (-not (Test-Path -Path HKLM:\SOFTWARE\Microsoft\PolicyManager\current\device\Education)) {
        New-Item -Path HKLM:\SOFTWARE\Microsoft\PolicyManager\current\device\Education -Force
    }
    New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PolicyManager\current\device\Education -Name IsEducationEnvironment -PropertyType DWord -Value 1 -Force

    # ---------------------------------------------------------
    Write-HostAndLog "Wyczanie hibernacji..."
    powercfg /hibernate off

    # ---------------------------------------------------------
    Write-HostAndLog "Set power plan on High performance. It isn't recommended to turn on for laptops"
    POWERCFG /SETACTIVE SCHEME_MIN

    # ---------------------------------------------------------
    Write-HostAndLog "Wycz upienie na zasilaniu sieciowym"
    powercfg /change standby-timeout-ac 0  
    Write-HostAndLog "Wycz upienie na baterii (dla laptopw)"
    powercfg /change standby-timeout-dc 0
    Write-HostAndLog "Wycz wygaszanie ekranu na zasilaniu sieciowym"  
    powercfg /change monitor-timeout-ac 0  
    Write-HostAndLog "Wycz wygaszanie ekranu na baterii (dla laptopw)"
    powercfg /change monitor-timeout-dc 0  

    # ---------------------------------------------------------
    Write-HostAndLog "Wyczanie funkcji Fast Startup..."
    Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power" -Name "HiberbootEnabled" -Value 0 -Force

    # ---------------------------------------------------------
    Write-HostAndLog "Display Stop error code when BSoD occurs"
    New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl -Name DisplayParameters -PropertyType DWord -Value 1 -Force

    # ---------------------------------------------------------
    Write-HostAndLog "Turn off Delivery Optimization"
    New-ItemProperty -Path Registry::HKEY_USERS\S-1-5-20\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings -Name DownloadMode -PropertyType DWord -Value 0 -Force
    Delete-DeliveryOptimizationCache -Force

    # ---------------------------------------------------------
    Write-HostAndLog "Do not allow the computer to turn off the network adapters to save power."
    #  It isn't recommended to turn off for laptops
    # Checking whether there's an adapter that has AllowComputerToTurnOffDevice property to manage
    # We need also check for adapter status per some laptops have many equal adapters records in adapters list
    $Adapters = Get-NetAdapter -Physical | Where-Object -FilterScript { $_.MacAddress -and ($_.Status -eq "Up") } | Get-NetAdapterPowerManagement | Where-Object -FilterScript { $_.AllowComputerToTurnOffDevice -ne "Unsupported" }
    if (-not $Adapters) {
        Write-Information -MessageData "" -InformationAction Continue
        Write-Verbose -Message ($Localization.Skipped -f $MyInvocation.Line.Trim()) -Verbose
        Write-Error -Message ($Localization.Skipped -f $MyInvocation.Line.Trim()) -ErrorAction SilentlyContinue
        return
    }
    foreach ($Adapter in $Adapters) {
        $Adapter.AllowComputerToTurnOffDevice = "Disabled"
        $Adapter | Set-NetAdapterPowerManagement
    }

    # ---------------------------------------------------------
    Write-HostAndLog "Wyczanie rezerwowanego miejsca na dysku..."
    Set-WindowsReservedStorageState -State Disabled

    # ---------------------------------------------------------
    # ------------------------------------------------------------
    Write-HostAndLog "Wyczanie funkcji Wi-Fi Sense..."
    Set-ItemProperty -Path "HKLM:\Software\Microsoft\WcmSvc\wifinetworkmanager\config" -Name "AutoConnectAllowedOEM" -Value 0
    Set-ItemProperty -Path "HKLM:\Software\Microsoft\WcmSvc\wifinetworkmanager\config" -Name "WiFiSenseAllowed" -Value 0

    # ------------------------------------------------
    Write-HostAndLog "Wyczanie Cortany..."

    # cieka rejestru
    $regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Windows Search"

    try {
        # Tworzenie klucza, jeli nie istnieje
        if (-not (Test-Path $regPath)) {
            New-Item -Path $regPath -Force | Out-Null
            Write-HostAndLog "Utworzono klucz rejestru: $regPath"
        }

        # Ustawienie wartoci AllowCortana na 0
        Set-ItemProperty -Path $regPath -Name "AllowCortana" -Value 0 -Type DWord -Force -ErrorAction Stop
        Write-HostAndLog "Cortana zostaa wyczona w rejestrze."
    }
    catch {
        Write-HostAndLog "Bd podczas wyczania Cortany: $_"
        Show-Except
    }

    # Opcjonalne: zatrzymanie procesu Cortany, jeli dziaa
    $cortanaProcess = Get-Process -Name "Cortana" -ErrorAction SilentlyContinue
    if ($cortanaProcess) {
        Stop-Process -Name "Cortana" -Force -ErrorAction SilentlyContinue
        Write-HostAndLog "Zatrzymano proces Cortany."
    }


    # ---------------------------------------------
    Write-HostAndLog "Wyczanie funkcji Timeline..."
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System" -Name "EnableActivityFeed" -Value 0 -Force
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System" -Name "PublishUserActivities" -Value 0 -Force
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System" -Name "UploadUserActivities" -Value 0 -Force


    Write-HostAndLog "Ustawienienia tapety START"

    # Ustawienia Polityk Grupy (Policies)
    $regPath2 = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization"
    if (-not (Test-Path $regPath2)) { New-Item -Path $regPath2 -Force | Out-Null }
    Set-ItemProperty -Path $regPath2 -Name "LockScreenImage" -Value $wallpaperPath -ErrorAction SilentlyContinue
    Set-ItemProperty -Path $regPath2 -Name "NoChangingLockScreen" -Value 1 -ErrorAction SilentlyContinue

    # Ustawienia OEMBackground
    $regPath3 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background"
    if (-not (Test-Path $regPath3)) { New-Item -Path $regPath3 -Force | Out-Null }
    Set-ItemProperty -Path $regPath3 -Name "OEMBackground" -Value 1 -ErrorAction SilentlyContinue

    # Ustawienia PersonalizationCSP
    $regPath4 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP"
    if (-not (Test-Path $regPath4)) { New-Item -Path $regPath4 -Force | Out-Null }
    Set-ItemProperty -Path $regPath4 -Name "LockScreenImagePath" -Value $wallpaperPath -ErrorAction SilentlyContinue
    Set-ItemProperty -Path $regPath4 -Name "LockScreenImageStatus" -Value 1 -ErrorAction SilentlyContinue

    # Upewnij si, e obraz ma uprawnienia do odczytu przez system
    $acl = Get-Acl -Path $wallpaperPath
    $permission = "NT AUTHORITY\SYSTEM", "ReadAndExecute", "Allow"
    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.SetAccessRule($accessRule)
    Set-Acl -Path $wallpaperPath -AclObject $acl



    # Odwieenie ustawie (komentarz: w praktyce to rzadko pomaga, ale nie zaszkodzi)
    # Start-Process "ms-settings:lockscreen"
    # Start-Sleep -Seconds 3
    # [System.Windows.Forms.SendKeys]::SendWait("{ESC}")

    Write-HostAndLog "To ekranu blokady i logowania zostao zmienione"

    # ---------------------------
    # KONIEC: Zmiana ta ekranu blokady i pulpitu
    # ---------------------------


}


# Disable "News and Interests" on the taskbar
function NewsInterests {
    param
    (
        [Parameter(
            Mandatory = $true,
            ParameterSetName = "Disable"
        )]
        [switch]
        $Disable,

        [Parameter(
            Mandatory = $true,
            ParameterSetName = "Enable"
        )]
        [switch]
        $Enable
    )

    # Remove all policies in order to make changes visible in UI only if it's possible
    Remove-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Windows Feeds" -Name EnableFeeds -Force -ErrorAction Ignore
    Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PolicyManager\default\NewsAndInterests\AllowNewsAndInterests" -Name value -Force -ErrorAction Ignore

    if (-not (Get-Package -Name "Microsoft Edge" -ProviderName Programs -ErrorAction Ignore)) {
        Write-Information -MessageData "" -InformationAction Continue
        Write-Verbose -Message ($Localization.Skipped -f $MyInvocation.Line.Trim()) -Verbose
        Write-Error -Message ($Localization.Skipped -f $MyInvocation.Line.Trim()) -ErrorAction SilentlyContinue

        return
    }

    # We have to use GetValue() due to "Set-StrictMode -Version Latest"
    $MachineId = [Microsoft.Win32.Registry]::GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SQMClient", "MachineId", $null)
    if (-not $MachineId) {
        Write-Information -MessageData "" -InformationAction Continue
        Write-Verbose -Message ($Localization.Skipped -f $MyInvocation.Line.Trim()) -Verbose
        Write-Error -Message ($Localization.Skipped -f $MyInvocation.Line.Trim()) -ErrorAction SilentlyContinue

        return
    }

    # https://forums.mydigitallife.net/threads/taskbarda-widgets-registry-change-is-now-blocked.88547/#post-1849006
    $Signature = @{
        Namespace          = "WinAPI"
        Name               = "Signature"
        Language           = "CSharp"
        CompilerParameters = $CompilerParameters
        MemberDefinition   = @"
[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
public static extern int HashData(byte[] pbData, int cbData, byte[] piet, int outputLen);
"@
    }
    if (-not ("WinAPI.Signature" -as [type])) {
        Add-Type @Signature
    }

    # We cannot set a value to EnShellFeedsTaskbarViewMode, having called any of APIs, except of copying powershell.exe (or any other tricks) with a different name, due to a UCPD driver tracks all executables to block the access to the registry
    Copy-Item -Path "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -Destination "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Force

    switch ($PSCmdlet.ParameterSetName) {
        "Disable" {
            # Combine variables into a string
            $Combined = $MachineId + '_' + 2
            # Reverse the whole string
            $CharArray = $Combined.ToCharArray()
            [array]::Reverse($CharArray)
            $Reverse = -join $CharArray
            $bytesIn = [System.Text.Encoding]::Unicode.GetBytes($Reverse)
            $bytesOut = [byte[]]::new(4)
            [WinAPI.Signature]::HashData($bytesIn, 0x53, $bytesOut, $bytesOut.Count)
            # Get value to save in EnShellFeedsTaskbarViewMode key
            $DWordData = [System.BitConverter]::ToUInt32($bytesOut, 0)

            & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Command { New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Feeds -Name ShellFeedsTaskbarViewMode -PropertyType DWord -Value 2 -Force }
            # We need to use here an approach with "-Command & {}" as there's a variable inside
            & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Command "& {New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Feeds -Name EnShellFeedsTaskbarViewMode -PropertyType DWord -Value $DWordData -Force}"
        }
        "Enable" {
            # Combine variables into a string
            $Combined = $MachineId + '_' + 0
            # Reverse the whole string
            $CharArray = $Combined.ToCharArray()
            [array]::Reverse($CharArray)
            $Reverse = -join $CharArray
            $bytesIn = [System.Text.Encoding]::Unicode.GetBytes($Reverse)
            $bytesOut = [byte[]]::new(4)
            [WinAPI.Signature]::HashData($bytesIn, 0x53, $bytesOut, $bytesOut.Count)
            # Get value to save in EnShellFeedsTaskbarViewMode key
            $DWordData = [System.BitConverter]::ToUInt32($bytesOut, 0)

            & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Command { New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Feeds -Name ShellFeedsTaskbarViewMode -PropertyType DWord -Value 0 -Force }
            # We need to use here an approach with "-Command & {}" as there's a variable inside
            & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Command "& {New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Feeds -Name EnShellFeedsTaskbarViewMode -PropertyType DWord -Value $DWordData -Force}"
        }
    }

    Remove-Item -Path "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell_temp.exe" -Force
}





function Clean-Disk {
    Write-HostAndLog "Czyszczenie dysku i usuwanie zbdnych plikw..."

    Get-PSDrive C

    # Czyszczenie dysku

    # Oczyszczanie folderw temp
    Remove-Item -Path "$env:TEMP\*" -Force -Recurse -ErrorAction SilentlyContinue
    Remove-Item -Path "C:\Windows\Temp\*" -Force -Recurse -ErrorAction SilentlyContinue

    # Usu logi systemowe
    Remove-Item -Path "C:\Windows\Logs\*" -Force -Recurse -ErrorAction SilentlyContinue

    # Usu stare pliki Windows Update
    Write-HostAndLog "Czyszczenie folderu WinSxS..."
    Write-HostAndLog "Uruchamianie DISM w celu oczyszczenia obrazu systemu..."
    Start-Process -FilePath "dism.exe" -ArgumentList "/Online /Cleanup-Image /StartComponentCleanup /ResetBase" -Wait -NoNewWindow
    Write-HostAndLog "DISM zakoczy dziaanie."

    # Usu stare punkty przywracania systemu
    # Usuwanie wszystkich punktw przywracania systemu
    Get-ComputerRestorePoint | ForEach-Object {
        Write-HostAndLog "Usuwanie punktu przywracania ID: $($_.SequenceNumber)"
        Checkpoint-Computer -Description "TemporaryCheckpoint" -RestorePointType APPLICATION_INSTALL
        Disable-ComputerRestore -Drive "C:\"
    }

    # Wyczenie przywracania systemu:
    Disable-ComputerRestore -Drive "C:\"

    # Uruchom oczyszczanie dysku
    Write-HostAndLog "Uruchamianie cleanmgr i oczekiwanie na zakoczenie jego dziaania..."
    Start-Process -FilePath "cleanmgr.exe" -ArgumentList "/sagerun:1" -Wait -NoNewWindow
    Write-HostAndLog "cleanmgr zakoczy dziaanie."

    Get-PSDrive C

    Write-HostAndLog "Czyszczenie zakoczone!"
}



function End-Main {
    Write-HostAndLog "Restart Eksploratora Windows, aby zastosowa zmiany"
    Stop-Process -Name "explorer" -Force -ErrorAction SilentlyContinue
    Start-Sleep -Milliseconds 500
    Start-Process "explorer"

    Write-HostAndLog "Skrypt zakoczony. Zrestartuj komputer, aby zastosowa wszystkie zmiany."
    Write-Host " Zrestartuj komputer, aby zastosowa wszystkie zmiany. " -ForegroundColor White -BackgroundColor Red

    Write-Host "Czy chcesz zrestartowa komputer? (T/N)" -ForegroundColor Yellow
    $restart = Read-Host
    if ($restart -eq "T") {
        Restart-Computer -Force
    }
    else {
        Write-HostAndLog "Restart zosta anulowany."
    }
}

function Add-Admin {
    # Odczytaj zalogowanego uytkownika
    $currentLoggedInUser = $env:USERNAME

    Write-Host "Skrypt doda noweg administratora i usunie z administratorow zalogowanego uzytkownika ($currentLoggedInUser)"
    $confirmation = Read-Host "Kontynuowac? (T/N)"

    # Normalizacja odpowiedzi uytkownika (ignorowanie wielkoci liter)
    switch ($confirmation.ToUpper()) {
        "T" { Write-Host "Kontynuuje skrypt..." }
        "N" { Write-Host "Skrypt zostal przerwany."; return }
        default { Write-Host "Niepoprawna odpowiedz. Skrypt zostal przerwany."; return }
    }

    $userLogin = Read-Host "Podaj nazwe konta administratora [myadmin]"
    if ([string]::IsNullOrWhiteSpace($userLogin)) {
        $userLogin = "myadmin"
    }
    $userPassword = Read-Host -AsSecureString "Podaj haslo dla konta $userLogin"
    New-LocalUser -Name $userLogin -Password $userPassword -FullName "Administrator" -Description "Administrator $userLogin" -AccountNeverExpires

    # SID dla grupy "Administrators"
    $administratorsGroupSID = "S-1-5-32-544"
    Add-LocalGroupMember -SID $administratorsGroupSID -Member $userLogin

    # SID dla grupy "Users"
    $usersGroupSID = "S-1-5-32-545"
    Add-LocalGroupMember -SID $usersGroupSID -Member $currentLoggedInUser

    # Usu zalogowanego uytkownika z grupy "Administrators"
    Remove-LocalGroupMember -SID $administratorsGroupSID -Member $currentLoggedInUser

}

Start-Main