├── .test ├── dist │ └── .gitkeep └── excel.xlsx ├── .gitignore ├── choco ├── choco upgrade update all.bat ├── choco list installed packages - localonly.bat ├── choco upgrade update all and hibernate.bat └── choco-generate-config-from-current-configuration.ps1 ├── network ├── get-ip.bat └── ping-url.bat ├── debian ├── gen-cpu-load.sh ├── install-docker.sh └── tmux.md ├── ahk ├── mouse-control.ahk ├── swich-desktops-windows-10.ahk ├── sound-control.ahk └── swich-desktops-windows-10-mouse-only.ahk ├── uncategorized ├── computer-gender.vbs └── sync-dirs │ ├── README.md │ ├── unregister-watcher.ps1 │ └── register-watcher.ps1 ├── windows ├── identify-motherboard.ps1 └── ui interaction with powershell.ps1 ├── git ├── specify-user.ps1 ├── git-snippets.ps1 ├── add-submodule.ps1 ├── worktree.ps1 ├── github-api.ps1 ├── rewrite-git-history.sh ├── find-large-files.sh └── setup-ssh-for-git.ps1 ├── system-maintenance ├── remove-service.ps1 ├── remove-service-interactive.ps1 ├── create-file-snapshot.ps1 ├── update-hosts-file.ps1 └── dispose-expired-certificate.ps1 ├── system-setup ├── ms-edge-allow-localhost.ps1 ├── disable-windows-search-indexing.ps1 ├── set-env-PATH.ps1 ├── set-dns-server-addresses.ps1 ├── firewall-rules.ps1 └── disable-connected-devices-platform-services.ps1 ├── sql ├── contained database authentication.sql └── pihole │ ├── trim-domain.sql │ ├── adlist-unique-domains.sql │ └── globally-unique-domains.sql ├── README.md ├── security ├── get-file-hash.ps1 ├── get-random-password.ps1 ├── update-ACL.ps1 ├── ssl-ignore-certificate.ps1 ├── sandobox.wsb └── local-https-dev-setup.ps1 ├── development ├── ps-module │ ├── import-local-module.ps1 │ └── module-junction.ps1 ├── ps │ ├── convert-ps-to-exe.ps1 │ ├── pass-function-as-argument.ps1 │ ├── generic.ps1 │ ├── reflection.ps1 │ └── http-server.ps1 ├── refactoring │ └── remove-comments.ps1 ├── ci │ └── get-nuget.ps1 ├── .net │ ├── dotnet-publish.ps1 │ ├── update-net-framework-version.ps1 │ └── add-build-configuration-vs.ps1 ├── REST │ ├── slack-chat.postMessage.ps1 │ └── push-discordMessage.ps1 ├── snippets │ ├── convertfrom-string │ │ ├── powershell-template-parsing.ps1 │ │ └── powershell-template-parsing-l2.ps1 │ ├── jobs.ps1 │ ├── jobs-max-threads.ps1 │ └── get-specific-stream-output-only.ps1 ├── validation │ └── check-copyright.ps1 ├── environment-variables.ps1 ├── azure │ └── remove-azure-indexes.ps1 └── remove-bin-obj-packages-folders-for-given-path.ps1 ├── monitoring └── procmon │ ├── ProcmonConfigurationObsidian.pmc │ └── procmon-cli.ps1 ├── strings └── remove-non-ASCII-characters.ps1 ├── good-practices ├── foreach-object.ps1 ├── out-null.ps1 ├── where-object.ps1 ├── add-to-array.ps1 └── return.ps1 ├── data └── thispersondoesnotexist.ps1 ├── system-extensions ├── delayed-system-hibernate.bat ├── swich-off-screen.bat ├── process │ └── watch-process.ps1 └── swich-off-screen.ps1 ├── filesystem ├── rename-files-lastwritetime.ps1 └── gzip.ps1 ├── dsc ├── README.md ├── validate.dsc.yml ├── steps │ └── ExtensionManifestV2Availability.dsc.yml └── run.ps1 ├── wsl ├── refresh-debian.ps1 └── install-pwsh.sh ├── media ├── touch-image.ps1 ├── color-inversion.md └── ffmpeg.ps1 ├── .vscode └── settings.json ├── tasks └── register-scheduled-task.ps1 ├── file-processing └── split kml.ps1 ├── ps-cheat-sheet.ps1 ├── excel └── convert-xlsx-to-csv.ps1 └── regedit └── directory-prompts.reg /.test/dist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .test/dist/ 2 | -------------------------------------------------------------------------------- /choco/choco upgrade update all.bat: -------------------------------------------------------------------------------- 1 | choco upgrade all -y 2 | pause -------------------------------------------------------------------------------- /network/get-ip.bat: -------------------------------------------------------------------------------- 1 | powershell (wget icanhazip.com).Content 2 | pause -------------------------------------------------------------------------------- /choco/choco list installed packages - localonly.bat: -------------------------------------------------------------------------------- 1 | clist -lo 2 | pause -------------------------------------------------------------------------------- /debian/gen-cpu-load.sh: -------------------------------------------------------------------------------- 1 | yes > /dev/null & 2 | sleep 50 3 | kill $! 4 | -------------------------------------------------------------------------------- /ahk/mouse-control.ahk: -------------------------------------------------------------------------------- 1 | XButton1:: Send {Browser_Forward} 2 | XButton2:: Send {Browser_Back} -------------------------------------------------------------------------------- /uncategorized/computer-gender.vbs: -------------------------------------------------------------------------------- 1 | CreateObject("SAPI.SpVoice").Speak"Guess what is my gender" -------------------------------------------------------------------------------- /windows/identify-motherboard.ps1: -------------------------------------------------------------------------------- 1 | wmic baseboard get product, Manufacturer, version, serialnumber -------------------------------------------------------------------------------- /.test/excel.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PowerShellLibrary/Hacker-Scripts/HEAD/.test/excel.xlsx -------------------------------------------------------------------------------- /git/specify-user.ps1: -------------------------------------------------------------------------------- 1 | ## Specify user 2 | git config user.name "AuthorExample" 3 | git config user.email "ae@duck.com" -------------------------------------------------------------------------------- /system-maintenance/remove-service.ps1: -------------------------------------------------------------------------------- 1 | Get-Service | ? { $_.Name.Contains("xconnect") } | % { sc.exe delete $_.Name } -------------------------------------------------------------------------------- /system-setup/ms-edge-allow-localhost.ps1: -------------------------------------------------------------------------------- 1 | CheckNetIsolation LoopbackExempt -a -n="Microsoft.MicrosoftEdge_8wekyb3d8bbwe" -------------------------------------------------------------------------------- /git/git-snippets.ps1: -------------------------------------------------------------------------------- 1 | # create a new Git branch based on a specific commit SHA 2 | git checkout -b BRANCH_NAME COMMIT_SHA -------------------------------------------------------------------------------- /sql/contained database authentication.sql: -------------------------------------------------------------------------------- 1 | USE [master] 2 | GO 3 | sp_configure 'contained database authentication',1 4 | GO -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacker Scripts 2 | 3 | Power Shell scripts library for true **Power Users**. 4 | 5 | ❗ **Use at your own risk** -------------------------------------------------------------------------------- /security/get-file-hash.ps1: -------------------------------------------------------------------------------- 1 | Get-FileHash -Path "C:\file.txt" -Algorithm SHA512 2 | Get-FileHash -Path "C:\file.txt" -Algorithm MD5 -------------------------------------------------------------------------------- /development/ps-module/import-local-module.ps1: -------------------------------------------------------------------------------- 1 | Clear-Host; 2 | Remove-Module NullKit; 3 | Import-Module C:\repo\NullKit\NullKit.psd1; -------------------------------------------------------------------------------- /development/ps/convert-ps-to-exe.ps1: -------------------------------------------------------------------------------- 1 | # https://github.com/MScholtes/PS2EXE 2 | 3 | Install-Module ps2exe 4 | Invoke-ps2exe .\source.ps1 -------------------------------------------------------------------------------- /choco/choco upgrade update all and hibernate.bat: -------------------------------------------------------------------------------- 1 | choco upgrade all -y 2 | %windir%\system32\rundll32.exe powrprof.dll,SetSuspendState 3 | pause -------------------------------------------------------------------------------- /system-maintenance/remove-service-interactive.ps1: -------------------------------------------------------------------------------- 1 | Get-Service | Out-GridView -PassThru -Title "Select services for removal" | % { sc.exe delete $_.Name } -------------------------------------------------------------------------------- /development/ps-module/module-junction.ps1: -------------------------------------------------------------------------------- 1 | New-FolderJunction -Source C:\repo\NullKit -Destination "c:\Users\Alan\Documents\WindowsPowerShell\Modules\NullKit" -------------------------------------------------------------------------------- /git/add-submodule.ps1: -------------------------------------------------------------------------------- 1 | # Add new submodule 2 | git submodule add git://github.com/jquery/jquery.git externals/jquery 3 | git submodule update --init --recursive -------------------------------------------------------------------------------- /system-setup/disable-windows-search-indexing.ps1: -------------------------------------------------------------------------------- 1 | Get-Service -Name "*WSearch*" | Set-Service -StartupType Disabled 2 | Get-Service -Name "*WSearch*" | Stop-Service -------------------------------------------------------------------------------- /monitoring/procmon/ProcmonConfigurationObsidian.pmc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PowerShellLibrary/Hacker-Scripts/HEAD/monitoring/procmon/ProcmonConfigurationObsidian.pmc -------------------------------------------------------------------------------- /strings/remove-non-ASCII-characters.ps1: -------------------------------------------------------------------------------- 1 | $inputString = "żółć gęślą jaźń" 2 | [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes($inputString)) -------------------------------------------------------------------------------- /good-practices/foreach-object.ps1: -------------------------------------------------------------------------------- 1 | # BAD 2 | @(1, 2, 3) | Foreach-Object { 3 | # do stuff 4 | } 5 | 6 | # GOOD - 2x faster 7 | foreach ($i in @(1, 2, 3)) { 8 | # do stuff 9 | } -------------------------------------------------------------------------------- /data/thispersondoesnotexist.ps1: -------------------------------------------------------------------------------- 1 | 1..100 | % { 2 | Invoke-WebRequest -Uri "https://thispersondoesnotexist.com/image" -OutFile "D:\avatars\$([guid]::NewGuid()).jpg" 3 | Start-Sleep -Seconds 1 4 | } -------------------------------------------------------------------------------- /good-practices/out-null.ps1: -------------------------------------------------------------------------------- 1 | Measure-Command { $(1..10000) | Out-Null } | Select-Object -Property TotalMilliseconds 2 | Measure-Command { $(1..10000) > $null } | Select-Object -Property TotalMilliseconds -------------------------------------------------------------------------------- /system-extensions/delayed-system-hibernate.bat: -------------------------------------------------------------------------------- 1 | set /p Input=Enter delay in minutes: 2 | set /a result=%Input%*60 3 | timeout /t %result% 4 | %windir%\system32\rundll32.exe powrprof.dll,SetSuspendState -------------------------------------------------------------------------------- /filesystem/rename-files-lastwritetime.ps1: -------------------------------------------------------------------------------- 1 | Get-ChildItem "D:\___to backup\" | % { 2 | $date = $_.LastWriteTime.ToString("yyyy-MM-dd") 3 | $name = $_.Name 4 | $_ | Rename-Item -NewName "$date-$name" 5 | } -------------------------------------------------------------------------------- /network/ping-url.bat: -------------------------------------------------------------------------------- 1 | set /p Input=Enter URL: 2 | set /p Delay=Enter Delay [sec]: 3 | powershell "while(1 -eq 1){ Invoke-WebRequest '%Input%' | Select-Object -Property StatusCode, Content ; Start-Sleep -Seconds %Delay% }" -------------------------------------------------------------------------------- /development/refactoring/remove-comments.ps1: -------------------------------------------------------------------------------- 1 | $startPath = C:\repo\src 2 | 3 | Import-Module NullKit 4 | Get-ChildItem -Path $startPath -Filter "*.cs" -r ` 5 | | ? { ! $_.PSIsContainer } ` 6 | | % { Remove-Comments $_ } -------------------------------------------------------------------------------- /dsc/README.md: -------------------------------------------------------------------------------- 1 | # Desired State Configuration 3.0 2 | 3 | - [ExtensionManifestV2Availability.dsc](https://developer.chrome.com/docs/extensions/develop/migrate/mv2-deprecation-timeline) - enable support for chrome extensions V2 -------------------------------------------------------------------------------- /system-extensions/swich-off-screen.bat: -------------------------------------------------------------------------------- 1 | powershell (Add-Type '[DllImport(\"user32.dll\")]^public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1, 0x0112, 0xF170, 2) 2 | -------------------------------------------------------------------------------- /development/ci/get-nuget.ps1: -------------------------------------------------------------------------------- 1 | $nugetVersion = "6.7.0" # Change to your required version 2 | $nugetUrl = "https://dist.nuget.org/win-x86-commandline/v$nugetVersion/nuget.exe" 3 | Invoke-WebRequest -Uri $nugetUrl -OutFile "nuget.exe" -------------------------------------------------------------------------------- /wsl/refresh-debian.ps1: -------------------------------------------------------------------------------- 1 | # Refresh Debian WSL distribution by unregistering and reinstalling it. 2 | # This is useful when the distribution is corrupted or when you want to reset it. 3 | 4 | wsl -l -v 5 | wsl --unregister Debian 6 | wsl --install -d Debian -------------------------------------------------------------------------------- /dsc/validate.dsc.yml: -------------------------------------------------------------------------------- 1 | $schema: https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json 2 | 3 | resources: 4 | - name: Validate the OS is Windows 5 | type: Microsoft/OSInfo 6 | properties: 7 | family: Windows 8 | 9 | -------------------------------------------------------------------------------- /good-practices/where-object.ps1: -------------------------------------------------------------------------------- 1 | # BAD 2 | $array = @(1, 2, 3, 1, 3, 4) | Where-Object { $_ -eq 1 } 3 | 4 | # GOOD - x17 faster 5 | $array = @( 6 | foreach ($i in @(1, 2, 3, 1, 3, 4)) { 7 | if ($i -eq 1) { 8 | $i 9 | } 10 | } 11 | ) -------------------------------------------------------------------------------- /security/get-random-password.ps1: -------------------------------------------------------------------------------- 1 | # continuous ASCII table 2 | Get-Random -Minimum 32 -Maximum 123 -Count 20 | % { [char]$_ } | Join-String 3 | 4 | # selected ASCII table chunks 5 | $chars = 48..57 + 65..90 + 97..122 6 | 1..20 | % { $chars | Get-Random } | % { [char]$_ } | Join-String -------------------------------------------------------------------------------- /sql/pihole/trim-domain.sql: -------------------------------------------------------------------------------- 1 | -- Trim leading and trailing characters from the domain field in the gravity table 2 | UPDATE gravity 3 | SET domain = TRIM( 4 | TRIM(SUBSTR(domain, CASE WHEN domain LIKE '||%' THEN 3 ELSE 1 END), '^') 5 | ) 6 | WHERE adlist_id = 26; -------------------------------------------------------------------------------- /git/worktree.ps1: -------------------------------------------------------------------------------- 1 | # list all worktrees 2 | git worktree list 3 | 4 | # add a worktree to folder _branch using branch 'issues/templates_enabled_flag' 5 | git worktree add _branch issues/templates_enabled_flag 6 | 7 | # remove a worktree from folder _branch 8 | git worktree remove _branch 9 | -------------------------------------------------------------------------------- /ahk/swich-desktops-windows-10.ahk: -------------------------------------------------------------------------------- 1 | LWin & WheelUp:: 2 | ; Previous Desktop 3 | Send {LWin down}{Ctrl down}{Left down}{LWin up}{Ctrl up}{Left up} 4 | return 5 | 6 | LWin & WheelDown:: 7 | ; Next Desktop 8 | Send {LWin down}{Ctrl down}{Right down}{LWin up}{Ctrl up}{Right up} 9 | return 10 | -------------------------------------------------------------------------------- /system-setup/set-env-PATH.ps1: -------------------------------------------------------------------------------- 1 | # This script will add a tool folder path to the system environment variable (PATH) 2 | $tool = "C:\tools\dsc" 3 | $PATH = [Environment]::GetEnvironmentVariable("PATH") 4 | [Environment]::SetEnvironmentVariable("PATH", "$PATH;$tool", [System.EnvironmentVariableTarget]::Machine) -------------------------------------------------------------------------------- /development/.net/dotnet-publish.ps1: -------------------------------------------------------------------------------- 1 | dotnet publish -r win-x64 --self-contained -p:PublishSingleFile=true -c Release -o ./publish/win 2 | dotnet publish -r linux-x64 --self-contained -p:PublishSingleFile=true -c Release -o ./publish/linux 3 | dotnet publish -r osx-x64 --self-contained -p:PublishSingleFile=true -c Release -o ./publish/osx -------------------------------------------------------------------------------- /ahk/sound-control.ahk: -------------------------------------------------------------------------------- 1 | !Numpad0:: Send {Volume_Mute} 2 | *!WheelUp:: Send {Volume_Up 2} 3 | *!WheelDown:: Send {Volume_Down 2} 4 | !XButton1:: Send {Media_Prev} 5 | !XButton2:: Send {Media_Next} 6 | ScrollLock::Suspend 7 | !Numpad1::Run nircmdc setdefaultsounddevice "Speakers" ,,Hide 8 | !Numpad2::Run nircmdc setdefaultsounddevice "SPDIF Interface" ,,Hide -------------------------------------------------------------------------------- /choco/choco-generate-config-from-current-configuration.ps1: -------------------------------------------------------------------------------- 1 | $packages = clist -lo 2 | $match = $packages | ? { $_ -like "* packages installed." } 3 | $count = $packages.IndexOf($match) 4 | $packages | Select-Object -First $count | % { 5 | $i = $_.IndexOf(" ") 6 | "choco install " + $_.Substring(0, $i) + " -y" >> "$PSScriptRoot\choco.conf.bat" 7 | } -------------------------------------------------------------------------------- /development/REST/slack-chat.postMessage.ps1: -------------------------------------------------------------------------------- 1 | # https://api.slack.com/methods/chat.postMessage/test 2 | 3 | $headers = @{'Content-Type' = 'application/json' } 4 | $payload = @{ "text" = "This is sparta!" } 5 | 6 | Invoke-WebRequest -Uri "https://hooks.slack.com/services/XXXXXXX/YYYYYYY/ZZZZZZ" ` 7 | -Method Post ` 8 | -Headers $headers ` 9 | -Body ($payload | ConvertTo-Json ) | Out-Null -------------------------------------------------------------------------------- /good-practices/add-to-array.ps1: -------------------------------------------------------------------------------- 1 | # Adding to an array with += is much slower: 2 | 3 | $list = @() 4 | Measure-Command { 5 | foreach ($number in $(1..10000)) { 6 | $list += $number 7 | } 8 | } 9 | 10 | # than capturing the output of the loop directly: 11 | 12 | Measure-Command { 13 | $list = foreach ($number in $(1..10000)) { 14 | $number 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /dsc/steps/ExtensionManifestV2Availability.dsc.yml: -------------------------------------------------------------------------------- 1 | $schema: https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json 2 | resources: 3 | - name: Manifest V2 Availability 4 | type: Microsoft.Windows/Registry 5 | properties: 6 | keyPath: HKLM\SOFTWARE\Policies\Google\Chrome\ 7 | valueName: ExtensionManifestV2Availability 8 | valueData: 9 | DWord: 2 -------------------------------------------------------------------------------- /system-extensions/process/watch-process.ps1: -------------------------------------------------------------------------------- 1 | $processToWatch = "Everything" 2 | while (1 -eq 1) { 3 | $procs = Get-Process | ? { $_.name -eq $processToWatch } 4 | if ($procs.length -gt 0) { 5 | Write-Host "Found $($procs.length) occurrences of $processToWatch" 6 | while (1 -eq 1) { 7 | [console]::beep(500, 300) 8 | Start-Sleep -Seconds 1 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /system-extensions/swich-off-screen.ps1: -------------------------------------------------------------------------------- 1 | # https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand 2 | # WM_SYSCOMMAND 0x0112 3 | 4 | # SC_TASKLIST 0xF130 5 | # SC_MONITORPOWER 0xF170 6 | $type = Add-Type '[DllImport("user32.dll")]public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas 7 | 8 | $type::SendMessage(-1, 0x0112, 0xF130, -1) 9 | $type::SendMessage(-1, 0x0112, 0xF170, 2) -------------------------------------------------------------------------------- /security/update-ACL.ps1: -------------------------------------------------------------------------------- 1 | # Modifies access control lists (ACL) for a given directory 2 | $repoPath = "C:\repo\Hacker-Scripts" 3 | $user = "VICTORINOX\Alan" 4 | 5 | # checks current access 6 | $ACL = Get-Acl -Path $repoPath 7 | Write-Host "ACL.Owner: " $ACL.Owner -ForegroundColor Yellow 8 | 9 | # updates access 10 | $owner = New-Object System.Security.Principal.Ntaccount($user) 11 | $ACL.SetOwner($owner) 12 | Set-Acl -Path $repoPath -AclObject $ACL -------------------------------------------------------------------------------- /development/ps/pass-function-as-argument.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-Func($text, $predicate) { 2 | if ($predicate.Invoke($text) -eq $true) { 3 | Write-Host "Valid`t [$text]" -ForegroundColor Green 4 | } 5 | else { 6 | Write-Host "Invalid`t [$text]" -ForegroundColor Red 7 | } 8 | } 9 | 10 | function Test-Text($str) { 11 | $str.StartsWith("A") 12 | } 13 | 14 | Invoke-Func "ABC" ${function:Test-Text} 15 | Invoke-Func "XYZ" ${function:Test-Text} -------------------------------------------------------------------------------- /development/snippets/convertfrom-string/powershell-template-parsing.ps1: -------------------------------------------------------------------------------- 1 | $template = @' 2 | {[string]Name*:Phoebe Cat}, {[string]phone:425-123-6789}, {[int]age:6} 3 | {[string]Name*:Lucky}, {[string]phone:(206) 987-4321}, {[int]age:12} 4 | '@ 5 | 6 | $testText = @' 7 | Phoebe Cat, 425-123-6789, 6 8 | Lucky Shot, (206) 987-4321, 12 9 | Elephant Wise, 425-888-7766, 87 10 | Wild Shrimp, (111) 222-3333, 1 11 | '@ 12 | 13 | $testText | ConvertFrom-String -TemplateContent $template -------------------------------------------------------------------------------- /media/touch-image.ps1: -------------------------------------------------------------------------------- 1 | # Use case: modify media items without changing their visual content 2 | 3 | # Usage: touch all PNG files in the images directory 4 | # Get-ChildItem ".\themes\images\" -Filter *.png -Recurse | ForEach-Object { Touch-File $_.FullName } 5 | 6 | 7 | function Touch-File { 8 | param ([string]$filePath) 9 | 10 | $bytes = [System.IO.File]::ReadAllBytes($filePath) 11 | 12 | # Append a harmless zero byte 13 | $bytes += 0x00 14 | 15 | [System.IO.File]::WriteAllBytes($filePath, $bytes) 16 | } -------------------------------------------------------------------------------- /development/snippets/jobs.ps1: -------------------------------------------------------------------------------- 1 | $Block = { 2 | Param([string] $text) 3 | Write-Host "[start] $text" 4 | Start-Sleep -Seconds 4 5 | Write-Host "[end] $text" 6 | } 7 | 8 | $jobs = @() 9 | $jobs += Start-Job -Scriptblock $Block -ArgumentList "1st" 10 | Start-Sleep -Seconds 2 11 | $jobs += Start-Job -Scriptblock $Block -ArgumentList "2nd" 12 | Clear-Host 13 | While ($(Get-Job -State Running).count -gt 0) { 14 | start-sleep -Milliseconds 500 15 | $jobs | % { 16 | Receive-Job -Job $_ 17 | } 18 | } 19 | Get-Job | Remove-Job -------------------------------------------------------------------------------- /development/ps/generic.ps1: -------------------------------------------------------------------------------- 1 | # Workaround to call to a generic method OfType() in PowerShell, when PowerShell cannot figure out from the context 2 | 3 | # Method 1 - using OfType method 4 | [System.Linq.Enumerable]::OfType[int](@(1, 2, 'a')) 5 | 6 | # Method 2 - using reflection 7 | $method = [System.Linq.Enumerable].GetMethod('OfType') 8 | $genericMethod = $method.MakeGenericMethod([int]) 9 | $genericMethod.Invoke($null, @(, @(1, 2, 'a'))) 10 | 11 | # Example of using Distinct method 12 | [System.Linq.Enumerable]::Distinct([int[]]@(1, 2, 3, 1, 2)) -------------------------------------------------------------------------------- /git/github-api.ps1: -------------------------------------------------------------------------------- 1 | Clear-Host 2 | $PersonalAccessToken = "github_pat_[your_personal_access_token]" 3 | 4 | $GitHubApiUrl = "https://api.github.com/user/repos" 5 | # $GitHubApiUrl = "https://api.github.com/orgs/PowerShellLibrary/repos" 6 | # $GitHubApiUrl = "https://api.github.com/repositories" 7 | 8 | $Headers = @{ 9 | Authorization = "token $PersonalAccessToken" 10 | "User-Agent" = "PowerShell" # GitHub API requires a User-Agent header 11 | } 12 | 13 | $response = Invoke-RestMethod -Uri $GitHubApiUrl -Method Get -Headers $Headers 14 | $response 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | // "editor.fontFamily": "Cascadia Code, jetbrains mono, 'Courier New', monospace", // fallback fonts 3 | "editor.fontSize": 18, 4 | "workbench.colorTheme": "Default Dark Modern", 5 | "workbench.colorCustomizations": { 6 | "editor.lineHighlightBackground": "#202020", 7 | "editor.selectionHighlightBackground": "#141414", 8 | "editor.selectionHighlightBorder": "#b3ff00", 9 | "editor.background": "#0A0A0A" 10 | }, 11 | "files.defaultLanguage": "powershell", 12 | "files.associations": { 13 | "*.wsb": "xml" 14 | } 15 | } -------------------------------------------------------------------------------- /development/validation/check-copyright.ps1: -------------------------------------------------------------------------------- 1 | $StartPath = "C:\dlls" 2 | $ExpectedCopyright = "© 2018 Alan Płócieniak. All rights reserved." 3 | 4 | Get-ChildItem $StartPath | ? { $_.Extension -eq ".dll" } | % { 5 | $path = $_.FullName 6 | $versionInfo = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($path) 7 | $copyright = $versioninfo.LegalCopyright 8 | if ($copyright -ne $ExpectedCopyright) { 9 | Write-Host $path -ForegroundColor Red 10 | Write-Host $copyright 11 | } 12 | else { 13 | Write-Host $path -ForegroundColor Green 14 | } 15 | } -------------------------------------------------------------------------------- /windows/ui interaction with powershell.ps1: -------------------------------------------------------------------------------- 1 | # Focus Assist Off 2 | Add-Type -AssemblyName System.Windows.Forms 3 | [System.Windows.Forms.SendKeys]::SendWait("(^{ESC})") 4 | Start-Sleep -Milliseconds 500 5 | [System.Windows.Forms.SendKeys]::SendWait("(Focus Assist)") 6 | Start-Sleep -Milliseconds 200 7 | [System.Windows.Forms.SendKeys]::SendWait("{ENTER}") 8 | Start-Sleep -Milliseconds 700 9 | [System.Windows.Forms.SendKeys]::SendWait("{TAB}{TAB} ") 10 | Start-Sleep -Milliseconds 500 11 | [System.Windows.Forms.SendKeys]::SendWait("{ENTER}") 12 | Start-Sleep -Milliseconds 500 13 | [System.Windows.Forms.SendKeys]::SendWait("(%{F4})") -------------------------------------------------------------------------------- /git/rewrite-git-history.sh: -------------------------------------------------------------------------------- 1 | # usage 2 | #1. create run.sh 3 | #2. paste content 4 | #3. open bash 5 | #4. run 'bash run' 6 | 7 | #!/bin/sh 8 | git filter-branch --env-filter ' 9 | OLD_EMAIL="incorrect@gmail.com" 10 | CORRECT_NAME="Alan NULL" 11 | CORRECT_EMAIL="alan-null@outlook.com" 12 | 13 | if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ] 14 | then 15 | export GIT_COMMITTER_NAME="$CORRECT_NAME" 16 | export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL" 17 | fi 18 | if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ] 19 | then 20 | export GIT_AUTHOR_NAME="$CORRECT_NAME" 21 | export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL" 22 | fi 23 | ' --tag-name-filter cat -- --branches --tags -------------------------------------------------------------------------------- /monitoring/procmon/procmon-cli.ps1: -------------------------------------------------------------------------------- 1 | # This script is used to start Process Monitor in the background with a specific configuration file. 2 | # https://learn.microsoft.com/en-us/sysinternals/downloads/procmon 3 | 4 | procmon.exe /Quiet /Minimized /LoadConfig ProcmonConfigurationObsidian.pmc /Backingfile MonitorLog.pml 5 | 6 | # Configuration File: ProcmonConfigurationObsidian.pmc 7 | 8 | # Monitoring Activities 9 | # Show Process and Thread Activity 10 | # Show Network Activity 11 | 12 | # Capture Events (Drop filtered events) 13 | # Filters 14 | # - ✅Process Name is Obsidian.exe 15 | # - ❌Operation is NOT Thread Create 16 | # - ❌Operation is NOT Thread Exit 17 | # - ❌Operation is NOT Load Image -------------------------------------------------------------------------------- /system-maintenance/create-file-snapshot.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [parameter(Mandatory = $true, Position = 0)] 3 | [string]$fileToBackup, 4 | [parameter(Mandatory = $true, Position = 1)] 5 | [string]$backupFolderPath 6 | ) 7 | Import-Module NullKit 8 | 9 | $current = Get-Location 10 | try { 11 | Set-Location $backupFolderPath 12 | if (!(Test-GitRepo)) { 13 | git init 14 | } 15 | 16 | if (Test-GitRepo) { 17 | Copy-Item -Path $fileToBackup -Destination $backupFolderPath -Force 18 | git add . 19 | $date = Get-Date 20 | git commit -m "$date" 21 | } 22 | } 23 | catch{ 24 | Write-Error $_.Exception 25 | } 26 | finally { 27 | Set-Location $current 28 | } 29 | -------------------------------------------------------------------------------- /system-setup/set-dns-server-addresses.ps1: -------------------------------------------------------------------------------- 1 | Write-Host '1: Cloudflare' 2 | Write-Host '2: Google' 3 | $dnsProviderIndex = Read-Host 'DNS provider: ' 4 | if ($dnsProviderIndex -eq 2) { 5 | $DNS = ("8.8.8.8", "8.8.4.4", "2001:4860:4860::8888", "2001:4860:4860::8844") 6 | } 7 | else { 8 | $DNS = ("1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001") 9 | } 10 | 11 | $interfaces = Get-NetIPInterface 12 | $interfaces 13 | $ifIndex = Read-Host 'ifIndex: ' 14 | $interface = $interfaces | ? { $_.ifIndex -eq "$ifIndex" } 15 | if ($interface) { 16 | Set-DnsClientServerAddress -InterfaceIndex $ifIndex -ServerAddresses $DNS 17 | } 18 | else { 19 | Write-Error "Could not find network inteface with a given index" 20 | } 21 | -------------------------------------------------------------------------------- /wsl/install-pwsh.sh: -------------------------------------------------------------------------------- 1 | # Source: https://learn.microsoft.com/en-us/powershell/scripting/install/install-debian?view=powershell-7.5 2 | 3 | # Update the list of packages 4 | sudo apt-get update 5 | 6 | # Install pre-requisite packages. 7 | sudo apt-get install -y wget 8 | 9 | # Download the PowerShell package file 10 | wget https://github.com/PowerShell/PowerShell/releases/download/v7.5.0/powershell_7.5.0-1.deb_amd64.deb 11 | 12 | # Install the PowerShell package 13 | sudo dpkg -i powershell_7.5.0-1.deb_amd64.deb 14 | 15 | # Resolve missing dependencies and finish the install (if necessary) 16 | sudo apt-get install -f 17 | 18 | # Delete the downloaded package file 19 | rm powershell_7.5.0-1.deb_amd64.deb 20 | 21 | # Start PowerShell 22 | pwsh -------------------------------------------------------------------------------- /uncategorized/sync-dirs/README.md: -------------------------------------------------------------------------------- 1 | # Dir Sync 2 | Helper to keep directories synchronized. 3 | 4 | Script will create a `IO.FileSystemWatcher` and observe following events. 5 | 6 | - FileDeleted 7 | - FileCreated 8 | - FileChanged 9 | 10 | If any of those events will occur, defined action will be triggered. 11 | 12 | ## Scripts 13 | 14 | - unregister-watcher.ps1 - used to unregister handlers 15 | - register-watcher.ps1 - used to register handlers 16 | 17 | # Usage 18 | 19 | ### register example 20 | ```powershell 21 | .\register-watcher.ps1 -SourceIdentifier GitBackupHandler -Source "C:\src" -Destination "D:\backup" 22 | ``` 23 | 24 | ### unregister example 25 | ```powershell 26 | .\unregister-watcher.ps1 -SourceIdentifier GitBackupHandler 27 | ``` 28 | -------------------------------------------------------------------------------- /development/snippets/jobs-max-threads.ps1: -------------------------------------------------------------------------------- 1 | $Block = { 2 | Param([string] $text) 3 | Write-Host "[start] $text" 4 | Start-Sleep -Seconds 4 5 | Write-Host "[end] $text" 6 | } 7 | 8 | function Show-Jobs { 9 | param ($jobs) 10 | $jobs | % { Receive-Job -Job $_ } 11 | } 12 | 13 | Clear-Host 14 | $jobs = @() 15 | $MaxThreads = 4 16 | 1..50 | % { 17 | #Start jobs. Max 4 jobs running simultaneously. 18 | While ($(Get-Job -state running).count -ge $MaxThreads) { 19 | Start-Sleep -Milliseconds 100 20 | Show-Jobs $jobs 21 | } 22 | $jobs += Start-Job -Scriptblock $Block -ArgumentList $_ 23 | } 24 | 25 | While ($(Get-Job -State Running).count -gt 0) { 26 | start-sleep -Milliseconds 100 27 | Show-Jobs $jobs 28 | } -------------------------------------------------------------------------------- /development/.net/update-net-framework-version.ps1: -------------------------------------------------------------------------------- 1 | # configuration 2 | $targetFramework = "net48" 3 | $startPath = "C:\repo\src" 4 | # configuration - END 5 | 6 | Clear-Host 7 | Get-ChildItem -Path $startPath -Recurse -ErrorAction SilentlyContinue | ? { $_.Extension -eq ".csproj" } | % { 8 | Write-Host "Processing $_" -ForegroundColor Green 9 | [xml]$xmlDoc = Get-Content $_.FullName 10 | [System.Xml.XmlNode]$node = $xmlDoc.Project.PropertyGroup.ChildNodes | ? { $_.Name -eq "TargetFramework" } 11 | if ($node.InnerText -ne $targetFramework) { 12 | Write-Host "`tChanking value from '$($node.InnerText)' to '$targetFramework'" -ForegroundColor DarkCyan 13 | $node.InnerText = $targetFramework 14 | $xmlDoc.Save($_.FullName) 15 | } 16 | } -------------------------------------------------------------------------------- /system-setup/firewall-rules.ps1: -------------------------------------------------------------------------------- 1 | # Block a ABCD.exe from accessing the Internet using Windows Defender Firewall 2 | $exePath = "C:\Users\Alan\AppData\Local\Programs\ABCD\ABCD.exe" 3 | 4 | # Add outbound rule to block ABCD.exe 5 | New-NetFirewallRule -DisplayName "[Block] ABCD Out" -Direction Outbound -Program $exePath -Action Block 6 | 7 | # Add inbound rule to block ABCD.exe 8 | New-NetFirewallRule -DisplayName "[Block] ABCD In" -Direction Inbound -Program $exePath -Action Block 9 | 10 | # Enable rules 11 | Get-NetFirewallRule -DisplayName "[Block] ABCD" | Set-NetFirewallRule -Enabled True 12 | 13 | # Disable the inbound rule 14 | Get-NetFirewallRule -DisplayName "*Block* ABCD In" | Set-NetFirewallRule -Enabled False 15 | 16 | # Remove rules 17 | Get-NetFirewallRule -DisplayName '*ABCD*' | Remove-NetFirewallRule -------------------------------------------------------------------------------- /debian/install-docker.sh: -------------------------------------------------------------------------------- 1 | # Add Docker's official GPG key: 2 | sudo apt-get update 3 | sudo apt-get install ca-certificates curl 4 | sudo install -m 0755 -d /etc/apt/keyrings 5 | sudo curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc 6 | sudo chmod a+r /etc/apt/keyrings/docker.asc 7 | 8 | # Add the repository to Apt sources: 9 | ARCH=$(dpkg --print-architecture) 10 | CODENAME=$(source /etc/os-release && echo "$VERSION_CODENAME") 11 | REPO_URL="deb [arch=$ARCH signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian $CODENAME stable" 12 | echo "$REPO_URL" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null 13 | 14 | sudo apt-get update 15 | 16 | # Install latest version 17 | sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -------------------------------------------------------------------------------- /git/find-large-files.sh: -------------------------------------------------------------------------------- 1 | git rev-list --objects --all | 2 | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | 3 | sed -n 's/^blob //p' | 4 | awk '$2 >= 2^20' | 5 | sort --numeric-sort --key=2 | 6 | cut -c 1-12,41- | 7 | $(command -v gnumfmt || echo numfmt) --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest 8 | 9 | # example output 10 | # 22c19f287836 1.0MiB images/posts/1.gif 11 | # 0e15a02b835a 1.2MiB images/posts/2.gif 12 | # f48d3086bf1d 1.5MiB images/posts/3.gif 13 | # eecf2e1d46a7 1.6MiB images/posts/4.gif 14 | # a267f286e7f2 1.7MiB images/posts/5.gif 15 | # 225cba92676b 3.4MiB images/posts/6.gif 16 | 17 | # to find commits with SHA use 18 | # git log --raw --all --find-object=225cba92676b 19 | 20 | # to find all files with given extension 21 | # git log --all --full-history -- *.gif -------------------------------------------------------------------------------- /ahk/swich-desktops-windows-10-mouse-only.ahk: -------------------------------------------------------------------------------- 1 | SetTitleMatchMode, RegEx 2 | #IfWinNotActive ^.*YouTube.*$ 3 | 4 | *WheelDown:: 5 | { 6 | if InsideLoop=1 7 | { 8 | ActionInvoked = 1 9 | Send {LWin down}{Ctrl down}{Right down}{LWin up}{Ctrl up}{Right up} 10 | return 11 | } 12 | send, {blind}{WheelDown} 13 | return 14 | } 15 | 16 | *WheelUp:: 17 | { 18 | if InsideLoop=1 19 | { 20 | ActionInvoked = 1 21 | Send {LWin down}{Ctrl down}{Left down}{LWin up}{Ctrl up}{Left up} 22 | return 23 | } 24 | send, {blind}{WheelUp} 25 | return 26 | } 27 | 28 | $RButton:: 29 | { 30 | ActionInvoked = 0 31 | InsideLoop = 32 | While GetKeyState("RButton", "p") 33 | { 34 | InsideLoop = 1 35 | } 36 | InsideLoop = 37 | if ActionInvoked = 0 38 | send, {blind}{RButton} 39 | } 40 | 41 | #IfWinNotActive -------------------------------------------------------------------------------- /tasks/register-scheduled-task.ps1: -------------------------------------------------------------------------------- 1 | $name = [guid]::NewGuid() 2 | $trigger = New-ScheduledTaskTrigger -Once -At 9am 3 | $principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest 4 | 5 | # inline script 6 | $action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& { Write-Host 1 }"' 7 | # file script 8 | $action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoLogo -WindowStyle hidden -file C:\script.ps1' 9 | 10 | $task = Register-ScheduledTask ` 11 | -TaskName $name ` 12 | -Description "Background task" ` 13 | -Trigger $trigger ` 14 | -Action $action ` 15 | -TaskPath '\Alan\jobs' ` 16 | -Principal $principal 17 | 18 | Write-Host "Created: $($task.TaskName) under $($task.TaskPath)" 19 | 20 | # display tasks in folder 21 | Get-ScheduledTask -TaskPath "\Alan\*" -------------------------------------------------------------------------------- /development/environment-variables.ps1: -------------------------------------------------------------------------------- 1 | # Environment Variable Lifetimes 2 | 3 | # 1. Session ($env:VARIABLE) 4 | $env:MY_VAR = "value1" 5 | Write-Host $env:MY_VAR 6 | 7 | # 1.1. Environment variable with dynamic key 8 | $key = "MY_VAR" 9 | Set-Item "env:$key" "value2" 10 | 11 | # 2. Process-Level Inheritance 12 | # when you set an environment variable in PowerShell, 13 | # it is inherited by child processes (like dotnet run, git, or other spawned applications). 14 | 15 | # 3. Permanent Environment Variables (Registry) 16 | [System.Environment]::SetEnvironmentVariable("MY_VAR", "value1", "User") 17 | Write-Host $env:MY_VAR 18 | 19 | # 4. Environment Variables in GitHubs Actions 20 | # Environment variables set during one step are not automatically available in subsequent steps in GitHub Actions. 21 | # To persist environment variables between steps, you need to explicitly use the GITHUB_ENV file. 22 | $value = "value1" 23 | echo "$key=$value" >> $env:GITHUB_ENV -------------------------------------------------------------------------------- /development/.net/add-build-configuration-vs.ps1: -------------------------------------------------------------------------------- 1 | $startPath = "C:\repo\src" 2 | 3 | Clear-Host 4 | Get-ChildItem -Path $startPath -Recurse -ErrorAction SilentlyContinue | ? { $_.Extension -eq ".csproj" } | ? { $_.Name.EndsWith(".Tests.csproj" ) -ne $true } | % { 5 | Write-Host "Processing $_" -ForegroundColor Green 6 | [xml]$xmlDoc = Get-Content $_ 7 | $node = $xmlDoc.Project.PropertyGroup | ? { $_.Condition -and $_.Condition.Contains("Release") } 8 | $escrowNode = $node.Clone() 9 | $escrowNode.Condition = $escrowNode.Condition.Replace("Release", "Escrow") 10 | $xmlDoc.Project.InsertAfter($escrowNode, $node) | Out-Null 11 | 12 | $configurationParent = $xmlDoc.Project.PropertyGroup | ? { $_.Condition -eq $null } 13 | 14 | $configurationsNode = $xmlDoc.CreateElement("Configurations") 15 | $configurationsNode.InnerXml = "Debug;Release;Escrow" 16 | $configurationParent.AppendChild($configurationsNode) 17 | $xmlDoc.Save($_.FullName) 18 | } -------------------------------------------------------------------------------- /development/REST/push-discordMessage.ps1: -------------------------------------------------------------------------------- 1 | # https://discord.com/developers/docs/resources/webhook#execute-webhook 2 | 3 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 4 | function Push-DiscordMessage { 5 | [CmdletBinding()] 6 | param ( 7 | [string]$hookUrl, 8 | $payload 9 | ) 10 | 11 | process { 12 | Invoke-RestMethod -Uri $hookUrl -Method Post -Body ($payload | ConvertTo-Json -Depth 4) -ContentType 'Application/Json' 13 | } 14 | } 15 | 16 | $hookUrl = 'https://discord.com/api/webhooks/XXXXXXX/YYYYYYY' 17 | $content = @" 18 | :green_circle: Server [YVES] is now ONLINE 19 | *$(Get-Date)* 20 | "@ 21 | 22 | $imgUrl = "https://avatars.githubusercontent.com/u/6848691" 23 | $payload = @{ 24 | content = $content; 25 | username = "Alan" ; 26 | avatar_url = $imgUrl; 27 | embeds = @( 28 | @{title = 'Header1'; thumbnail = @{ url = $imgUrl } } 29 | ) 30 | } 31 | Push-DiscordMessage $hookUrl $payload -------------------------------------------------------------------------------- /uncategorized/sync-dirs/unregister-watcher.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [parameter(Mandatory = $true)] 3 | [string]$SourceIdentifier 4 | ) 5 | 6 | $eventSubscribers = Get-EventSubscriber 7 | Write-Host "Before [$($eventSubscribers.Count)]" -ForegroundColor Red 8 | 9 | $events = @("HC::FileDeleted:$SourceIdentifier", "HC::FileCreated:$SourceIdentifier", "HC::FileChanged:$SourceIdentifier") 10 | foreach ($eventName in $events) { 11 | $eSub = Get-EventSubscriber | ? { $_.SourceIdentifier -eq $eventName } 12 | Write-Host "Get-EventSubscriber: $eventName" 13 | if ($eSub) { 14 | Unregister-Event $eventName 15 | Write-Host "Unregister-Event $eventName" -ForegroundColor Yellow 16 | } 17 | } 18 | 19 | $count = $eventSubscribers.Count 20 | $eventSubscribers = Get-EventSubscriber 21 | if ($eventSubscribers.Count -lt $count) { 22 | Write-Host "After [$($eventSubscribers.Count)]" -ForegroundColor Green 23 | }else { 24 | Write-Host "None unregistered." -ForegroundColor Green 25 | } -------------------------------------------------------------------------------- /file-processing/split kml.ps1: -------------------------------------------------------------------------------- 1 | $kmlPath = 'C:\big.kml' 2 | $max = 240 3 | $partsFolder = "$PSScriptRoot\parts" 4 | 5 | [xml]$doc = Get-Content -Path $kmlPath 6 | mkdir $partsFolder -ErrorAction SilentlyContinue | Out-Null 7 | $i = 1 8 | do { 9 | [xml]$clone = $doc.Clone() 10 | $clone.ChildNodes[0].Encoding = $null 11 | 12 | # remove everything except max number count (i.e 240, 480, 720) 13 | $clone.kml.Document.Folder.Placemark | Select-Object -Skip ($max * $i) | % { 14 | $clone.kml.Document.Folder.RemoveChild($_) | Out-Null 15 | } 16 | 17 | # buffering - selecting last max number count 18 | while ($clone.kml.Document.Folder.Placemark.Count -gt $max) { 19 | $clone.kml.Document.Folder.Placemark | Select-Object -First 1 | % { 20 | $clone.kml.Document.Folder.RemoveChild($_) | Out-Null 21 | } 22 | } 23 | 24 | $clone.Save("$partsFolder\_part2_$($i).kml") 25 | $i++ 26 | } 27 | while ($max * $i -le $doc.kml.Document.Folder.Placemark.Count) -------------------------------------------------------------------------------- /sql/pihole/adlist-unique-domains.sql: -------------------------------------------------------------------------------- 1 | -- This SQL query retrieves the number of unique domains and total domains for each adlist from the vw_gravity view. 2 | -- It calculates the uniqueness percentage and orders the results by this percentage in ascending order. 3 | 4 | SELECT 5 | adlist_id, 6 | COUNT(DISTINCT domain) AS unique_domains, 7 | COUNT(domain) AS total_domains, 8 | ROUND(CAST(COUNT(DISTINCT domain) AS FLOAT) / COUNT(domain) * 100, 2) AS uniqueness_percent 9 | FROM 10 | vw_gravity 11 | GROUP BY 12 | adlist_id 13 | ORDER BY 14 | uniqueness_percent ASC; 15 | 16 | 17 | -- Example output: 18 | -- adlist_id unique_domains total_domains uniqueness_percent 19 | -- 7 30873 31461 98.13 20 | -- 6 42363 42536 99.59 21 | -- 1 106610 106611 100.0 22 | -- 2 2194 2194 100.0 23 | -- 3 162079 162079 100.0 24 | -- 4 319548 319548 100.0 25 | -- 5 307383 307383 100.0 -------------------------------------------------------------------------------- /security/ssl-ignore-certificate.ps1: -------------------------------------------------------------------------------- 1 | function IgnoreSSL { 2 | if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type) { 3 | $certCallback = @" 4 | using System; 5 | using System.Net; 6 | using System.Net.Security; 7 | using System.Security.Cryptography.X509Certificates; 8 | public class ServerCertificateValidationCallback 9 | { 10 | public static void Ignore() 11 | { 12 | if(ServicePointManager.ServerCertificateValidationCallback ==null) 13 | { 14 | ServicePointManager.ServerCertificateValidationCallback += delegate 15 | ( 16 | Object obj, 17 | X509Certificate certificate, 18 | X509Chain chain, 19 | SslPolicyErrors errors 20 | ){ return true; }; 21 | } 22 | } 23 | } 24 | "@ 25 | Add-Type $certCallback 26 | } 27 | [ServerCertificateValidationCallback]::Ignore() 28 | } 29 | -------------------------------------------------------------------------------- /development/azure/remove-azure-indexes.ps1: -------------------------------------------------------------------------------- 1 | # configuration 2 | $apiKey = "[_API_KEY_]" 3 | $serviceName = "[_SERVICE_NAME_]" 4 | $apiVer = "2015-02-28-Preview" 5 | 6 | $headers = @{'Content-Type' = 'application/json'; 'api-key' = $apiKey } 7 | $baseUrl = "https://$($serviceName).search.windows.net/indexes" 8 | 9 | function Get-Index { 10 | param () 11 | $response = Invoke-WebRequest -Method Get -Uri "$baseUrl/?api-version=$apiVer" -Headers $headers 12 | $indexList = $response.Content | ConvertFrom-Json 13 | $indexList[0].value 14 | } 15 | 16 | function Remove-Index { 17 | param ([string]$iName) 18 | $remUrl = "$baseUrl/$iName/?api-version=$apiVer" 19 | Write-Host "Removing index: $iName" -ForegroundColor Yellow 20 | $response = Invoke-WebRequest -Method Delete -Uri $remUrl -Headers $headers 21 | $response.StatusCode -eq 204 22 | } 23 | 24 | (Get-Index).name | ? { $_.StartsWith("test-index-") } | % { 25 | if (Remove-Index $_) { 26 | Write-Host "[OK]" -ForegroundColor Green 27 | } 28 | else { 29 | Write-Host "[ERROR]" -ForegroundColor Red 30 | } 31 | Start-Sleep -Milliseconds 500 32 | } -------------------------------------------------------------------------------- /development/ps/reflection.ps1: -------------------------------------------------------------------------------- 1 | # constructor 2 | $constructorInfo = [System.IO.FileInfo].GetConstructor([string].AsType()) 3 | $constructorInfo = [System.IO.FileInfo].GetConstructor("public,instance", $types) 4 | $constructorInfo.Invoke('C:\Windows') 5 | 6 | # private field 7 | $obj = [System.IO.FileInfo]::new('C:\Windows') 8 | $field = [System.IO.FileInfo].GetField("_name", "nonpublic,instance") 9 | # longer version 10 | $field = [System.IO.FileInfo].GetField("_name", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance) 11 | $field.GetValue($obj) 12 | 13 | # private method - static 14 | $obj = $null 15 | $privMethod = [System.DateTime].GetMember("DateToTicks", "nonpublic,static") 16 | $privMethod.Invoke($obj, @(2023, 10, 10)) 17 | 18 | # private method - instance 19 | $obj = [System.DateTime]::Now 20 | $privMethod = [System.DateTime].GetMember("GetDatePart", "nonpublic,instance") 21 | $privMethod.Invoke($obj, @(0)) 22 | 23 | # private method - args requirements 24 | $privMethod = [System.DateTime].GetMethod("DateToTicks", "nonpublic,static", $null, @([int], [int], [int]), @()) 25 | $privMethod.Invoke($obj, @(2023, 10, 10)) -------------------------------------------------------------------------------- /dsc/run.ps1: -------------------------------------------------------------------------------- 1 | $validation = dsc config test -f .\validate.dsc.yml -o json | ConvertFrom-Json 2 | foreach ($r in $validation.results) { 3 | if ($r.result.inDesiredState -eq $false) { 4 | throw "[FAIL] $($r.name) [$($r.type)]" 5 | } 6 | } 7 | 8 | Get-ChildItem .\steps -Filter '*.dsc.yml' -Recurse | ForEach-Object { 9 | $step = $_.FullName 10 | Write-Host "[INFO] Running step: $step" -ForegroundColor DarkGray 11 | $test = dsc config test -f $step -o json | ConvertFrom-Json 12 | $test.results | % { 13 | if ($_.result.inDesiredState -eq $true) { 14 | Write-Host "[OK] $($_.name) [$($_.type)]" -ForegroundColor Green 15 | } 16 | else { 17 | Write-Host "[APPLY] $($_.name) [$($_.type)]" -ForegroundColor Yellow 18 | } 19 | } 20 | 21 | [bool[]]$states = $test.results.result.inDesiredState 22 | if ( $states.Contains($false)) { 23 | $setResult = dsc config set -f $step -o json | ConvertFrom-Json 24 | if ($LASTEXITCODE -ne 0) { 25 | throw "[FATAL] Couldn't set the desired state for $step" 26 | } 27 | } 28 | } 29 | 30 | if ($LASTEXITCODE -eq 0) { 31 | Write-Host "[PASS] All resources are in desired state" -ForegroundColor Green 32 | } -------------------------------------------------------------------------------- /security/sandobox.wsb: -------------------------------------------------------------------------------- 1 | 2 | Enable 3 | Enable 4 | Disable 5 | Disable 6 | Enable 7 | Disable 8 | Disable 9 | 10 | 11 | C:\sandbox\readonly 12 | true 13 | 14 | 15 | C:\sandbox\shared 16 | false 17 | 18 | 19 | 20 | 21 | explorer.exe C:\users\WDAGUtilityAccount\Downloads 22 | 23 | powershell.exe -executionpolicy unrestricted "C:\Users\WDAGUtilityAccount\Desktop\readonly\run.ps1" 24 | 25 | powershell -executionpolicy unrestricted -command "start powershell {-noexit -file C:\Users\WDAGUtilityAccount\Desktop\readonly\run.ps1}" 26 | 27 | -------------------------------------------------------------------------------- /sql/pihole/globally-unique-domains.sql: -------------------------------------------------------------------------------- 1 | -- This SQL query calculates the percentage of globally unique domains in each adlist from the vw_gravity view. 2 | -- Run trim-domain.sql before executing this query to ensure that the domain field is clean and trimmed. 3 | SELECT 4 | g1.adlist_id, 5 | COUNT(*) AS total_domains, 6 | SUM(CASE WHEN dup_counts.domain_count = 1 THEN 1 ELSE 0 END) AS globally_unique_domains, 7 | ROUND(SUM(CASE WHEN dup_counts.domain_count = 1 THEN 1.0 ELSE 0 END) / COUNT(*) * 100, 2) AS uniqueness_percent 8 | FROM 9 | vw_gravity g1 10 | JOIN ( 11 | SELECT domain, COUNT(DISTINCT adlist_id) AS domain_count 12 | FROM vw_gravity 13 | GROUP BY domain 14 | ) dup_counts ON g1.domain = dup_counts.domain 15 | GROUP BY 16 | g1.adlist_id 17 | ORDER BY 18 | uniqueness_percent DESC; 19 | 20 | -- Example output: 21 | -- adlist_id total_domains globally_unique_domains uniqueness_percent 22 | -- 4 319548 319548 100.0 23 | -- 2 2194 2194 100.0 24 | -- 7 31461 29665 94.29 25 | -- 1 106611 100485 94.25 26 | -- 6 42536 38253 89.93 27 | -- 5 307383 249377 81.13 28 | -- 3 162079 96220 59.37 -------------------------------------------------------------------------------- /development/snippets/get-specific-stream-output-only.ps1: -------------------------------------------------------------------------------- 1 | function Write-Messages { 2 | [CmdletBinding()] 3 | param() 4 | Write-Host "Host message" 5 | Write-Output "Output message" 6 | Write-Verbose "Verbose message" 7 | Write-Warning "Warning message" 8 | Write-Error "Error message" 9 | Write-Debug "Debug message" 10 | Write-Information "Information message" 11 | } 12 | 13 | # writes Error only 14 | Write-Messages -Verbose -Debug 2>&1 | Out-File -FilePath .\OutputFile.txt 15 | 16 | # writes Warning only 17 | Write-Messages -Verbose -Debug 3>&1 | Out-File -FilePath .\OutputFile.txt 18 | 19 | # writes Verbose only 20 | Write-Messages -Verbose -Debug 4>&1 | Out-File -FilePath .\OutputFile.txt 21 | 22 | # writes Debug only 23 | Write-Messages -Verbose -Debug 5>&1 | Out-File -FilePath .\OutputFile.txt 24 | 25 | # writes Information only 26 | Write-Messages -Verbose -Debug 6>&1 | Out-File -FilePath .\OutputFile.txt 27 | 28 | # writes Verbose and Debug 29 | Write-Messages -Verbose -Debug 5>&1 4>&1 | Out-File -FilePath .\OutputFile.txt 30 | 31 | # writes Verbose and Error from objec to a file 32 | $outStream = $( . { 33 | Write-Messages -Verbose 34 | Write-Messages -Verbose 35 | } | Out-Null) 2>&1 4>&1 36 | $outStream | Out-File -FilePath .\OutputFile.txt -------------------------------------------------------------------------------- /uncategorized/sync-dirs/register-watcher.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [parameter(Mandatory = $true, Position = 0)] 3 | [string]$SourceIdentifier, 4 | [parameter(Mandatory = $true, Position = 1)] 5 | [string]$Source, 6 | [parameter(Mandatory = $true, Position = 2)] 7 | [string]$Destination, 8 | [parameter(Mandatory = $false, Position = 3)] 9 | [string]$Filter = "*.*" 10 | ) 11 | 12 | $data = @{ src = $Source; dst = $Destination } 13 | $fsw = New-Object IO.FileSystemWatcher $Source, $Filter -Property @{IncludeSubdirectories = $true; NotifyFilter = [IO.NotifyFilters]"FileName, LastWrite"} 14 | 15 | $action = { 16 | $src = $event.MessageData.src 17 | $dst = $event.MessageData.dst 18 | $name = $Event.SourceEventArgs.Name 19 | $changeType = $Event.SourceEventArgs.ChangeType 20 | $timeStamp = $Event.TimeGenerated 21 | Write-Host "The file "$name" was $changeType at $timeStamp" -fore white 22 | Robocopy.exe $src $dst /MIR /Z /W:1 /R:1 23 | } 24 | 25 | Register-ObjectEvent $fsw Created -SourceIdentifier "HC::FileCreated:$SourceIdentifier" -Action $action -MessageData $data 26 | 27 | Register-ObjectEvent $fsw Deleted -SourceIdentifier "HC::FileDeleted:$SourceIdentifier" -Action $action -MessageData $data 28 | 29 | Register-ObjectEvent $fsw Changed -SourceIdentifier "HC::FileChanged:$SourceIdentifier" -Action $action -MessageData $data -------------------------------------------------------------------------------- /development/snippets/convertfrom-string/powershell-template-parsing-l2.ps1: -------------------------------------------------------------------------------- 1 | $template = @' 2 | {Name*:Bearded Keltir}([int]{Level:1}) Bearded Keltir location on the map {Type:Passive} {[int]Low:8}-{High:12} {Chance:70.00}% 3 | {Name*:Elpy}(1) Bearded Keltir location on the map {Type:Agressive} {[int]Low:8}-{High:1244} {Chance:100.00} 4 | '@ 5 | $testText = @' 6 | Bearded Keltir (1) Bearded Keltir location on the map Passive 8-12 70.00% 7 | Elpy (1) Elpy location on the map Passive 3-12 70.00% 8 | Gremlin (1) Gremlin location on the map Passive 7-13 100.00% 9 | Grey Elpy (1) Grey Elpy location on the map Aggresive 8-12 70.00% 10 | Young Brown Keltir (1) Young Brown Keltir location on the map Passive 8-12 70.00% 11 | Young Grey Keltir (1) Young Grey Keltir location on the map Passive 8-12 70.00% 12 | Young Keltir (1) Young Keltir location on the map Passive 8-12 70.00% 13 | Young Prairie Keltir (1) Young Prairie Keltir location on the map Passive 8-12 70.00% 14 | Young Red Keltir (1) Young Red Keltir location on the map Passive 8-12 70.00% 15 | Brown Keltir (2) Brown Keltir location on the map Passive 2-13 70.00% 16 | Grey Keltir (2) Grey Keltir location on the map Passive 1-13 70.00% 17 | '@ 18 | 19 | $testText | ` 20 | ConvertFrom-String -TemplateContent $template |` 21 | ? { [int]$_.Level -lt 68 } | ` 22 | Sort-Object -Property Low -Descending | Format-Table -------------------------------------------------------------------------------- /filesystem/gzip.ps1: -------------------------------------------------------------------------------- 1 | function ConvertFrom-Gzip { 2 | Param ( 3 | [Parameter(Mandatory = $true, ValueFromPipeline = $true)] 4 | [ValidateScript( { (Get-Item $_).Name.EndsWith(".gz") })] 5 | [System.IO.FileInfo] 6 | $InputObject, 7 | 8 | [Parameter(Mandatory = $false)] 9 | [switch] 10 | $RemoveInputFile 11 | ) 12 | Process { 13 | # Create a new file and open a filestream for it 14 | $NewFilename = $InputObject.FullName.Remove($InputObject.FullName.Length - $InputObject.Extension.Length) 15 | $DecompressedFileStream = [System.IO.File]::Create($NewFilename) 16 | 17 | # Open the compressed file and copy the file to the decompressed stream 18 | $CompressedFileStream = $InputObject.OpenRead() 19 | $GZipStream = [System.IO.Compression.GZipStream]::new($CompressedFileStream, [System.IO.Compression.CompressionMode]::Decompress) 20 | $GZipStream.CopyTo($DecompressedFileStream) 21 | 22 | # Cleanup 23 | $DecompressedFileStream.Dispose() 24 | $GZipStream.Dispose() 25 | $CompressedFileStream.Dispose() 26 | $DecompressedFileStream, $GZipStream, $CompressedFileStream = $null 27 | 28 | # Remove the initial file if requested. 29 | if ($PSBoundParameters.ContainsKey('RemoveInputFile')) { 30 | $InputObject.Delete() 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /git/setup-ssh-for-git.ps1: -------------------------------------------------------------------------------- 1 | # Prerequisites - you need to get SSH key supported by your git hosting service. 2 | # deploy it into: c:\id_rsa 3 | 4 | # generate SSH key 5 | ssh-keygen -t rsa -b 4096 -C "key-comment" # 4096 RSA key (SHA256) 6 | ssh-keygen -t ed25519 -C "key-comment" 7 | 8 | # install choco 9 | Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) 10 | 11 | # install dependencies 12 | choco install git -y 13 | 14 | # deploy SSH key into keys store 15 | $userName = [Environment]::UserName 16 | Write-Host "Username: $userName" -ForegroundColor Green 17 | Get-Item c:\id_rsa | Copy-Item -Destination "C:\Users\$userName\.ssh\id_rsa" 18 | 19 | # enable ssh service 20 | Get-Service -Name ssh-agent | Set-Service -StartupType Manual 21 | Start-Service ssh-agent 22 | 23 | # register ssh key 24 | ssh-add "C:\Users\$userName\.ssh\id_rsa" 25 | 26 | # register known_hosts 27 | ssh-keyscan bitbucket.org >> "C:\Users\$userName\.ssh\known_hosts" 28 | ssh-keyscan github.com >> "C:\Users\$userName\.ssh\known_hosts" 29 | ssh-keyscan vs-ssh.visualstudio.com >> "C:\Users\$userName\.ssh\known_hosts" 30 | 31 | # test connection to git repositories 32 | ssh -T ssh://alan-null@vs-ssh.visualstudio.com 33 | ssh -T git@bitbucket.org 34 | ssh -T git@github.com -------------------------------------------------------------------------------- /ps-cheat-sheet.ps1: -------------------------------------------------------------------------------- 1 | Clear-Host 2 | 3 | Write-Host "Get-Alias dir, cls" -ForegroundColor Green 4 | Get-Alias dir, cls 5 | 6 | Write-Host "Get-Command -Name get-* -Module NullKit" -ForegroundColor Green 7 | Get-Command -Name get-* -Module NullKit 8 | 9 | Write-Host "Get-Command -Module NullKit" -ForegroundColor Green 10 | Get-Command -Module NullKit 11 | 12 | Write-Host "Get-Command | Group-Object Verb | Sort-Object Count -Descending" -ForegroundColor Green 13 | Get-Command | Group-Object Verb | Sort-Object Count -Descending 14 | 15 | Write-Host "Get-Command | Group-Object Noun | Sort-Object Name" -ForegroundColor Green 16 | Get-Command | Group-Object Noun | Sort-Object Name | Sort-Object Count -Descending | Select-Object -First 10 17 | 18 | Get-Service | Sort-Object -Property @{expression = 'Status'; descending = $true }, @{expression = 'DisplayName'; descending = $false } 19 | 20 | Write-Host "[System.DateTime] | Get-Member -MemberType Method Get*" -ForegroundColor Green 21 | [System.DateTime] | Get-Member -MemberType Method Get* 22 | 23 | Write-Host Get-ItemProperty -ForegroundColor Green 24 | Get-Item "C:\Windows\System32\drivers\etc\hosts" | Get-ItemProperty | Format-List -Property * 25 | 26 | Write-Host "Get-Module -ListAvailable" -ForegroundColor Green 27 | Get-Module -ListAvailable 28 | 29 | Write-Host Get-WindowsOptionalFeature -ForegroundColor Green 30 | Get-WindowsOptionalFeature -Online -FeatureName *iis* 31 | #Enable-WindowsOptionalFeature -------------------------------------------------------------------------------- /system-maintenance/update-hosts-file.ps1: -------------------------------------------------------------------------------- 1 | $HostsFilePath = "C:\Windows\System32\drivers\etc\hosts" 2 | $Uri = "http://someonewhocares.org/hosts/hosts" 3 | $ValidationToken = "### someonewhocares" 4 | $ValidationTokenEnd = "### someonewhocares-end" 5 | 6 | function Get-NewHostsContent() { 7 | $hostsExtension = Invoke-WebRequest -Uri $Uri -UseBasicParsing 8 | $hostsExtension.Content -split "`n" | ? { Test-LineCorrect $_ } 9 | } 10 | 11 | function Test-LineCorrect ($line) { 12 | $_.StartsWith("127.0.0.1") -eq $true -or $_.StartsWith("#<") -or $_.StartsWith("# 10 | 11 | 12 | 13 | 14 | https://github.com/user-attachments/assets/a6969533-a1f9-4a8f-9203-dd151f4c6aa7 15 | 16 | #### After 17 | 18 | 21 | 22 | 23 | https://github.com/user-attachments/assets/16785da7-4ed3-48c5-ad3e-b1223987c49e 24 | 25 | 26 | ## Explanation 27 | The `-i input.mp4` part specifies the input file. 28 | 29 | The `-vf` flag stands for "video filter," and it is followed by a series of filters applied to the video. 30 | 31 | The filters are: 32 | 33 | - `negate`: This filter inverts the colors of the video, creating a negative effect. 34 | - `hue=h=180`: This filter adjusts the hue of the video by 180 degrees, effectively rotating the color wheel to change the overall color tone. 35 | - `eq=contrast=1.2:saturation=1.1`: This filter adjusts the contrast and saturation of the video. The contrast=1.2 increases the contrast by 20%, making the darks darker and the lights lighter. The saturation=1.1 increases the saturation by 10%, making the colors more vivid. 36 | 37 | 38 | 39 | Combining these filters results in a video with inverted colors, a shifted hue, and enhanced contrast and saturation. The processed video is then saved as output.mp4. 40 | 41 | 42 | *[source: 43 | Rubber Duck Thursdays!](https://www.youtube.com/watch?v=o7b6t6uZJPA)* -------------------------------------------------------------------------------- /system-maintenance/dispose-expired-certificate.ps1: -------------------------------------------------------------------------------- 1 | # Event Viewver log entry 2 | # Level Data and Time Source EventID Task Category 3 | # Warning 04-Dec-18 4:01:03 PM CertificateServicesClient-AutoEnrollment 64 None 4 | # 5 | # Event content 6 | # Certificate for local system with Thumbprint 3f ca 6f fa df 41 a3 6a 3b 5b c1 16 5c 7b ed 95 8c 49 65 50 is about to expire or already expired. 7 | 8 | $thumbprint = "3f ca 6f fa df 41 a3 6a 3b 5b c1 16 5c 7b ed 95 8c 49 65 50" 9 | $thumbprint = $thumbprint.ToUpperInvariant().Replace(" ", [string]::Empty) 10 | 11 | Set-Location CERT:\\ 12 | [System.Security.Cryptography.X509Certificates.X509Certificate2]$cert = Get-ChildItem -Recurse | ? { $_.Thumbprint -eq $thumbprint } | Select-Object -First 1 13 | if ($cert) { 14 | Write-Host "`nFriendlyName:" -ForegroundColor Green 15 | $cert.FriendlyName 16 | Write-Host "`nSubject:" -ForegroundColor Green 17 | $cert.Subject 18 | Write-Host "`nIssuer:" -ForegroundColor Green 19 | $cert.Issuer 20 | Write-Host "`nThumbprint:" -ForegroundColor Green 21 | $cert.Thumbprint 22 | Write-Host "`nNotBefore:" -ForegroundColor Green 23 | $cert.NotBefore 24 | Write-Host "`nNotAfter:" -ForegroundColor Green 25 | $cert.NotAfter 26 | $valid = $cert.Verify() 27 | Write-Host "`nVerify() => $($valid)" -ForegroundColor Green 28 | if($valid){ 29 | Write-Host "`nNothing to fix" -ForegroundColor Green 30 | }else{ 31 | Write-Host "`nNot VALID" -ForegroundColor Red 32 | Write-Host "`nTry to reset or dispose cert. First make sure that you've got other certificate issued from the same issuer" 33 | Write-Host "`nUse `$cert.Reset() or `$cert.Dispose()" 34 | # $cert.Reset() 35 | # $cert.Dispose() 36 | } 37 | }else { 38 | Write-Host "Cannot find certificate with a given Thumbprint '$thumbprint'" -ForegroundColor Yellow 39 | } -------------------------------------------------------------------------------- /system-setup/disable-connected-devices-platform-services.ps1: -------------------------------------------------------------------------------- 1 | # Potential problems: 2 | # WON'T WORK 3 | # - timeline WIN+TAB 4 | # MIGHT NOT WORK 5 | # - clipboard history sharing between devices 6 | # - Bluetooth file sharing 7 | # - Windows Night Light 8 | 9 | Clear-Host 10 | $Error.Clear() 11 | 12 | function Disable-CDPUserSvcViaRegistry { 13 | $baseRegistryPath = "HKLM:\SYSTEM\CurrentControlSet\Services" 14 | $cdpServices = Get-ChildItem -Path $baseRegistryPath | Where-Object { $_.Name -match "CDPUserSvc" } 15 | 16 | foreach ($service in $cdpServices) { 17 | Write-Host "Processing service: $($service.PSChildName)" -ForegroundColor Yellow 18 | try { 19 | # Set the 'Start' value to 4 (Disabled) at the root of the service key 20 | Set-ItemProperty -Path $service.PSPath -Name "Start" -Value 4 -ErrorAction Stop 21 | Write-Host "`tSuccessfully disabled service: $($service.PSChildName)" -ForegroundColor Green 22 | } 23 | catch { 24 | Write-Host "`tFailed to modify service: $($service.PSChildName). Error: $($_.Exception.Message)" -ForegroundColor Red 25 | } 26 | } 27 | } 28 | 29 | # Disable and stop CDPUserSvc 30 | Get-Service -Name 'CDPUserSvc*' | ForEach-Object { 31 | Stop-Service -Name $_.Name -Force 32 | try { 33 | Set-Service -Name $_.Name -StartupType Disabled -ErrorAction Stop 34 | } 35 | catch [Microsoft.PowerShell.Commands.ServiceCommandException] { 36 | Disable-CDPUserSvcViaRegistry 37 | } 38 | } 39 | 40 | # Disable and stop CDPSvc 41 | Write-Host "Processing service: CDPSvc" -ForegroundColor Yellow 42 | Stop-Service -Name CDPSvc -Force 43 | 44 | try { 45 | Set-Service -Name CDPSvc -StartupType Disabled 46 | Write-Host "`tSuccessfully disabled service: CDPSvc" -ForegroundColor Green 47 | 48 | } 49 | catch [Microsoft.PowerShell.Commands.ServiceCommandException] { 50 | write-host "`tFailed to modify service: CDPSvc. Error: $($_.Exception.Message)" -ForegroundColor Red 51 | } -------------------------------------------------------------------------------- /excel/convert-xlsx-to-csv.ps1: -------------------------------------------------------------------------------- 1 | # This is an example how to use Excel application using PowerShell (see \.test folder) 2 | # 3 | # Documentation 4 | # - https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.saveas 5 | # - https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.range 6 | # - https://docs.microsoft.com/en-us/office/vba/api/excel.range.copy 7 | # - https://docs.microsoft.com/en-us/office/vba/api/excel.sheets.select 8 | 9 | # test file 10 | $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition 11 | $excelFile = "$scriptPath\..\.test\excel.xlsx" 12 | 13 | # open Excel application 14 | $Excel = New-Object -ComObject Excel.Application 15 | # set visibility - show/hide window (background) 16 | $Excel.Visible = $true 17 | # open file 18 | $wb = $Excel.Workbooks.Open($excelFile) 19 | 20 | # add new sheet 21 | $ns = $wb.Worksheets.Add() 22 | # give it a name 23 | $ns.Name = "test" 24 | 25 | # select newly created empty sheet by index 26 | $wsEmpty = $wb.Worksheets.Item(1) 27 | $wsEmpty.Activate() 28 | # select cells (desitnation for copy action) - specify region 29 | $dst = $wsEmpty.Range("A1:B2") 30 | # select cells (desitnation for copy action) - invoke selection 31 | $dst.select() | Out-Null 32 | 33 | # switch to data sheet 34 | $wsData = $wb.Worksheets.Item(2) 35 | $wsData.Activate() 36 | # find index (when number of rows is different) 37 | $maxIndex = 6..38 | ? { $wsData.Cells.Item($_, 1).Value2 -eq $null } | Measure-Object -Minimum | % { $_.Minimum - 1 } 38 | $max = "K$maxIndex" 39 | # specify region for copy operation 40 | $data = $wsData.Range("A4:$max") 41 | 42 | # select region 43 | $data.select() | Out-Null 44 | # copy to destination (empty) 45 | $data.copy($dst) | Out-Null 46 | 47 | # switch to new/empty sheet 48 | $wsEmpty.Activate() 49 | # remove first row two times (i.e. column descriptors). For columns removal use '$wsEmpty.Columns(3).Delete()' 50 | 1..2 | % { $wsEmpty.Rows(1).Delete() | Out-Null } 51 | 52 | # save file as csv 53 | $wsEmpty.SaveAs("$scriptPath\..\.test\dist\excel.csv", 6) 54 | # close excel application 55 | $Excel.Quit() -------------------------------------------------------------------------------- /debian/tmux.md: -------------------------------------------------------------------------------- 1 | # Cheat Sheet: tmux 2 | 3 | ### 🏆 **Basic Commands:** 4 | 5 | ```bash 6 | tmux new -s abc # Create a new session named "abc" 7 | tmux ls # List all sessions 8 | tmux attach -t abc # Attach to a session 9 | tmux detach # Detach (Ctrl + B, then D also works) 10 | tmux switch-client -t abc # switch to the other session without nesting 11 | tmux kill-session -t abc # Kill a session 12 | tmux kill-server # Kill all sessions 13 | ``` 14 | 15 | --- 16 | 17 | ### ⚙️ **Pane Management:** 18 | 19 | | Action | Shortcut | 20 | | ----------------------------------- | ---------------------- | 21 | | **Split vertically (left/right)** | `Ctrl + B` → `%` | 22 | | **Split horizontally (top/bottom)** | `Ctrl + B` → `"` | 23 | | **Switch panes** | `Ctrl + B` → Arrow key | 24 | | **Close current pane** | `Ctrl + D` | 25 | | **Resize pane** | `Ctrl + B` → `:` then: | 26 | | Shrink down | `resize-pane -D 5` | 27 | | Shrink up | `resize-pane -U 5` | 28 | | Shrink left | `resize-pane -L 5` | 29 | | Shrink right | `resize-pane -R 5` | 30 | 31 | --- 32 | 33 | ### 🌐 **Window (Tab) Management:** 34 | 35 | | Action | Shortcut | 36 | | -------------------- | ---------------- | 37 | | **List windows** | `Ctrl + B` → `W` | 38 | | **Rename window** | `Ctrl + B` → `,` | 39 | | **New window (tab)** | `Ctrl + B` → `C` | 40 | | **Next window** | `Ctrl + B` → `N` | 41 | | **Previous window** | `Ctrl + B` → `P` | 42 | | **Close window** | `Ctrl + B` → `&` | 43 | 44 | --- 45 | 46 | ### 📌 **Session Management:** 47 | 48 | | Action | Shortcut | 49 | | ----------------------- | ------------------------------------- | 50 | | **Detach from session** | `Ctrl + B` → `D` | 51 | | **Switch sessions** | `Ctrl + B` → `S` | 52 | | **Rename session** | `Ctrl + B` → `$` | 53 | | **Kill session** | `Ctrl + B` → `:` then: `kill-session` | 54 | -------------------------------------------------------------------------------- /regedit/directory-prompts.reg: -------------------------------------------------------------------------------- 1 | Windows Registry Editor Version 5.00 2 | 3 | ; Command Prompt 4 | 5 | [HKEY_CLASSES_ROOT\Directory\shell\01MenuCmd] 6 | "MUIVerb"="Command Prompts" 7 | "Icon"="cmd.exe" 8 | "ExtendedSubCommandsKey"="Directory\\ContextMenus\\MenuCmd" 9 | 10 | [HKEY_CLASSES_ROOT\Directory\background\shell\01MenuCmd] 11 | "MUIVerb"="Command Prompts" 12 | "Icon"="cmd.exe" 13 | "ExtendedSubCommandsKey"="Directory\\ContextMenus\\MenuCmd" 14 | 15 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuCmd\shell\open] 16 | "MUIVerb"="Command Prompt" 17 | "Icon"="cmd.exe" 18 | 19 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuCmd\shell\open\command] 20 | @="cmd.exe /s /k pushd \"%V\"" 21 | 22 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuCmd\shell\runas] 23 | "MUIVerb"="Command Prompt Elevated" 24 | "Icon"="cmd.exe" 25 | "HasLUAShield"="" 26 | 27 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuCmd\shell\runas\command] 28 | @="cmd.exe /s /k pushd \"%V\"" 29 | 30 | 31 | ; PowerShell 32 | 33 | [HKEY_CLASSES_ROOT\Directory\shell\02MenuPowerShell] 34 | "MUIVerb"="PowerShell Prompts" 35 | "Icon"="powershell.exe" 36 | "ExtendedSubCommandsKey"="Directory\\ContextMenus\\MenuPowerShell" 37 | 38 | [HKEY_CLASSES_ROOT\Directory\background\shell\02MenuPowerShell] 39 | "MUIVerb"="PowerShell Prompts" 40 | "Icon"="powershell.exe" 41 | "ExtendedSubCommandsKey"="Directory\\ContextMenus\\MenuPowerShell" 42 | 43 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuPowerShell\shell\open] 44 | "MUIVerb"="PowerShell" 45 | "Icon"="powershell.exe" 46 | 47 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuPowerShell\shell\open\command] 48 | @="powershell.exe -noexit -command Set-Location '%V'" 49 | 50 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuPowerShell\shell\runas] 51 | "MUIVerb"="PowerShell Elevated" 52 | "Icon"="powershell.exe" 53 | "HasLUAShield"="" 54 | 55 | [HKEY_CLASSES_ROOT\Directory\ContextMenus\MenuPowerShell\shell\runas\command] 56 | @="powershell.exe -noexit -command Set-Location '%V'" 57 | 58 | 59 | ; Ensure OS Entries are on the Extended Menu (Shift-Right Click) 60 | 61 | [HKEY_CLASSES_ROOT\Directory\shell\cmd] 62 | "Extended"="" 63 | 64 | [HKEY_CLASSES_ROOT\Directory\background\shell\cmd] 65 | "Extended"="" 66 | 67 | [HKEY_CLASSES_ROOT\Directory\shell\Powershell] 68 | "Extended"="" 69 | 70 | [HKEY_CLASSES_ROOT\Directory\background\shell\Powershell] 71 | "Extended"="" -------------------------------------------------------------------------------- /media/ffmpeg.ps1: -------------------------------------------------------------------------------- 1 | # https://ffmpeg.org/ffmpeg.html 2 | 3 | # Takes two files (audio, video) and combine them together into mp4 file. 4 | # As audio is shorter add offset to the video so it can sync with audio 5 | # 6 | # -y (global) - overwrite output files without asking. 7 | # -itsoffset 0.2 - delay video by 0.2 seconds 8 | # -i v.webm - first input - video 9 | # -i a.mp4 - second input - audio 10 | # -map 0:0 - map stream 0 to output from input1 11 | # -map 1:0 - map stream 1 to output from input2 12 | # -c - for -c[:stream_specifier] codec. copy (output only) to indicate that the stream is not to be re-encoded 13 | ffmpeg -y -itsoffset 0.2 -i v.webm -i a.mp4 -map 0:0 -map 1:0 -c copy oFilename.mp4 14 | 15 | 16 | # Converts wav to mp3 17 | # 18 | # -i path input - mp3 19 | # -vn disable video 20 | # -ar rate set audio sampling rate (in Hz) 21 | # -ac channels set number of audio channels 22 | # -ab bitrate audio bitrate (please use -b:a) 23 | ffmpeg -i "$($_.FullName)" -vn -ar 44100 -ac 2 -b:a 192k "$($_.FullName.Replace('.wav','.mp3'))" 24 | 25 | 26 | # Takes two files (audio, image) and combine them together into mp4 file. 27 | # -loop 1 - loop the input image infinitely (1 - loop, 0 - no loop) 28 | # -i img.jpg - specifies an input file (image) 29 | # -i audio.mp3 - second input file (MP3 audio) 30 | # -c:v libx264 - specifies the video codec 31 | # -c:a aac - specifies the audio codec. aac is a standard codec for MP4 files, offering good quality at lower bitrates. 32 | # -b:a 320k - sets the audio bitrate 33 | # -shortest - this option ensures that the output video will be as long as the shortest input. 34 | # output.mp4 - name of the output video file 35 | ffmpeg -loop 1 -i img.jpg -i audio.mp3 -c:v libx264 -c:a aac -b:a 320k -shortest output.mp4 36 | 37 | # Crop video from the top 38 | # This command crops the video by removing 440 pixels from the top, effectively shifting the video down by that amount. 39 | # -i input.mp4 - specifies the input video file 40 | # -vf "crop=iw:ih-440:0:440" - applies a video filter (vf) to crop the video. 41 | # - iw Input width (keeps the full width of the video). 42 | # - ih-440 Input height minus 440 pixels 43 | # - 0 X offset (starts cropping from the left edge). 44 | # - 440 Y offset (starts cropping from 440 pixels down from the top). 45 | # -c:a copy - copies the audio stream without re-encoding it 46 | # output.mp4 - name of the output video file 47 | ffmpeg -i .\input.mp4 -vf "crop=iw:ih-440:0:440" -c:a copy output.mp4 -------------------------------------------------------------------------------- /development/ps/http-server.ps1: -------------------------------------------------------------------------------- 1 | $http = [System.Net.HttpListener]::new() 2 | $http.Prefixes.Add("http://localhost:8080/") 3 | $http.Start() 4 | 5 | if ($http.IsListening) { 6 | write-host " HTTP Server Ready! " -ForegroundColor White -BackgroundColor Green 7 | write-host "now try going to $($http.Prefixes)" -f 'y' 8 | write-host "then try going to $($http.Prefixes)other/path" -f 'y' 9 | } 10 | 11 | Start-Process 'http://localhost:8080/' 12 | Start-Process 'http://localhost:8080/some/form' 13 | 14 | try { 15 | while ($http.IsListening) { 16 | $contextTask = $http.GetContextAsync() 17 | while (-not $contextTask.AsyncWaitHandle.WaitOne(200)) { } 18 | $context = $contextTask.GetAwaiter().GetResult() 19 | 20 | # ROUTE EXAMPLE 1 21 | # http://127.0.0.1/ 22 | if ($context.Request.HttpMethod -eq 'GET' -and $context.Request.RawUrl -eq '/') { 23 | write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag' 24 | 25 | [string]$html = "

A Powershell Webserver

home page

" 26 | 27 | $buffer = [System.Text.Encoding]::UTF8.GetBytes($html) # convert htmtl to bytes 28 | $context.Response.ContentLength64 = $buffer.Length 29 | $context.Response.OutputStream.Write($buffer, 0, $buffer.Length) #stream to broswer 30 | $context.Response.OutputStream.Close() # close the response 31 | } 32 | 33 | # ROUTE EXAMPLE 2 34 | # http://127.0.0.1/some/form' 35 | if ($context.Request.HttpMethod -eq 'GET' -and $context.Request.RawUrl -eq '/some/form') { 36 | write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag' 37 | 38 | [string]$html = " 39 |

A Powershell Webserver

40 |
41 |

A Basic Form

42 |

fullname

43 | 44 |

message

45 | 46 |
47 | 48 |
49 | " 50 | $buffer = [System.Text.Encoding]::UTF8.GetBytes($html) 51 | $context.Response.ContentLength64 = $buffer.Length 52 | $context.Response.OutputStream.Write($buffer, 0, $buffer.Length) 53 | $context.Response.OutputStream.Close() 54 | } 55 | 56 | # ROUTE EXAMPLE 3 57 | # http://127.0.0.1/some/post' 58 | if ($context.Request.HttpMethod -eq 'POST' -and $context.Request.RawUrl -eq '/some/post') { 59 | 60 | $FormContent = [System.IO.StreamReader]::new($context.Request.InputStream).ReadToEnd() 61 | 62 | write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag' 63 | Write-Host $FormContent -f 'Green' 64 | 65 | [string]$html = "

A Powershell Webserver

Post Successful!

" 66 | 67 | $buffer = [System.Text.Encoding]::UTF8.GetBytes($html) 68 | $context.Response.ContentLength64 = $buffer.Length 69 | $context.Response.OutputStream.Write($buffer, 0, $buffer.Length) 70 | $context.Response.OutputStream.Close() 71 | } 72 | } 73 | } 74 | finally { 75 | $http.Stop() 76 | } -------------------------------------------------------------------------------- /development/remove-bin-obj-packages-folders-for-given-path.ps1: -------------------------------------------------------------------------------- 1 | function Get-FolderSize($folder) { 2 | $files = Get-ChildItem $folder.FullName -Recurse | ? { ! $_.PSIsContainer } | ? { $_.Length -ne $null} 3 | $size = $files | Measure-Object -Property length -Sum 4 | ($size.sum / 1MB) 5 | } 6 | 7 | function Get-FoldersToRemove { 8 | [CmdletBinding()] 9 | param( 10 | [Parameter(Mandatory = $true, Position = 0 )] 11 | [string]$StartPath 12 | ) 13 | 14 | begin { 15 | Write-Verbose "Cmdlet Get-FoldersToRemove - Begin" 16 | $foldersToRemove = @() 17 | } 18 | 19 | process { 20 | Write-Verbose "Cmdlet Get-FoldersToRemove - Process" 21 | Get-ChildItem -Path $StartPath -Recurse -ErrorAction SilentlyContinue | ? { $_.Extension -eq ".csproj" } | % { 22 | Write-Verbose "[CSPROJ]: $($_.FullName)" 23 | 24 | $binPath = "$($_.Directory)/bin" 25 | if (Test-Path $binPath) { 26 | Write-Verbose "`t[BIN]:`t`t $binPath" 27 | $binFolder = Get-Item -Path $binPath 28 | $foldersToRemove += $binFolder 29 | } 30 | 31 | $objPath = "$($_.Directory)/obj" 32 | if (Test-Path $objPath) { 33 | Write-Verbose "`t[OBJ]:`t`t $objPath" 34 | $objFolder = Get-Item -Path $objPath 35 | $foldersToRemove += $objFolder 36 | } 37 | 38 | [xml]$csproj = Get-Content -Path $_.FullName 39 | if ($csproj.Project.ItemGroup.None.Include | ? { $_ -eq "packages.config" }) { 40 | $prjcRelativePath = $csproj.Project.ItemGroup.Reference.HintPath | ? { $_ -ne $null -and $_.Length -gt 0 } | ? { $_.Contains("\packages\") } | Select-Object -First 1 41 | if ($prjcRelativePath -ne $null) { 42 | 43 | 44 | $path = [System.IO.Path]::GetFullPath((Join-Path $_.DirectoryName $prjcRelativePath )) 45 | if (Test-Path $path) { 46 | $dllFile = Get-Item -Path $path 47 | $packagesFolder = $dllFile 48 | 49 | while ($packagesFolder.Name -ne "packages" -and $packagesFolder.Parent -ne $packagesFolder) { 50 | $packagesFolder = Get-Item $packagesFolder.PSParentPath 51 | } 52 | 53 | if ($foldersToRemove.Length -eq 0 -or ($foldersToRemove.FullName.Contains($packagesFolder.FullName) -eq $false)) { 54 | Write-Verbose "`t[PACKAGES]:`t $packagesFolder" 55 | $foldersToRemove += $packagesFolder 56 | } 57 | } 58 | } 59 | } 60 | } 61 | $foldersToRemove 62 | } 63 | 64 | end { 65 | Write-Verbose "Cmdlet Get-FoldersToRemove - End" 66 | } 67 | } 68 | 69 | function Clear-VisualStudioProjectFolder { 70 | [CmdletBinding()] 71 | param( 72 | [Parameter(Mandatory = $true, Position = 0 )] 73 | [string]$StartPath 74 | ) 75 | 76 | begin { 77 | Write-Verbose "Cmdlet Clear-VisualStudioProjectFolder - Begin" 78 | } 79 | 80 | process { 81 | Write-Verbose "Cmdlet Clear-VisualStudioProjectFolder - Process" 82 | $memoryToRelease = 0 83 | $foldersToRemove = Get-FoldersToRemove $StartPath 84 | $foldersToRemove | % {$memoryToRelease += Get-FolderSize $_ } 85 | $foldersToRemove | Sort-Object -Property LastWriteTime -Descending | Format-Table FullName, LastWriteTime, @{Expression = { "{0:N2}" -f (Get-FolderSize $_) }; Label = "Size [MB]" } -AutoSize 86 | 87 | Write-Host ("Memory to release {0:N2}" -f $memoryToRelease + " MB") -ForegroundColor Green 88 | 89 | if ($memoryToRelease -eq 0) { 90 | Exit 91 | } 92 | 93 | Write-Host "WARNING: If you type 'Y', all folders listed above will be moved removed." -ForegroundColor Red 94 | $confirmation = Read-Host "Are you Sure You Want To Proceed" 95 | if ($confirmation -eq 'y') { 96 | $foldersToRemove | % { $_.Delete($true) } 97 | } 98 | } 99 | 100 | end { 101 | Write-Verbose "Cmdlet Clear-VisualStudioProjectFolder - End" 102 | } 103 | } 104 | 105 | Clear-VisualStudioProjectFolder "C:\repo\" -------------------------------------------------------------------------------- /security/local-https-dev-setup.ps1: -------------------------------------------------------------------------------- 1 | # --------------------------------------------- 2 | # LOCAL HTTPS SETUP FOR DEVELOPMENT 3 | # --------------------------------------------- 4 | 5 | $ErrorActionPreference = "Stop" 6 | 7 | # --- CONFIG --- 8 | $dns = "localhost" 9 | $port = 19456 10 | $friendlyName = "Dev Local HTTPS Cert" 11 | 12 | $storeLocationRoot = "LocalMachine" 13 | $storeNameRoot = "Root" 14 | 15 | $storeLocationMy = "LocalMachine" 16 | $storeNameMy = "My" 17 | 18 | $prefix = "https://$dns`:$port/" 19 | 20 | Write-Host "==============================================" 21 | Write-Host " HTTPS Setup for Local Secure Communication " 22 | Write-Host "==============================================" 23 | Write-Host "" 24 | 25 | # Ensure administrator 26 | if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { 27 | 28 | Write-Host "[ERROR] This script must be run as Administrator." -ForegroundColor Red 29 | exit 1 30 | } 31 | 32 | # --------------------------------------------- 33 | # Step 1 — Check/create certificate 34 | # --------------------------------------------- 35 | Write-Host "🔍 Checking for existing certificate..." -ForegroundColor Cyan 36 | 37 | $myStore = New-Object System.Security.Cryptography.X509Certificates.X509Store($storeNameMy, $storeLocationMy) 38 | $myStore.Open("ReadWrite") 39 | 40 | $existingCert = $myStore.Certificates | ? { $_.FriendlyName -eq $friendlyName } 41 | 42 | if ($existingCert) { 43 | Write-Host "✔ Found existing certificate: $friendlyName" -ForegroundColor Green 44 | $cert = $existingCert 45 | } 46 | else { 47 | Write-Host "⏳ Creating new self-signed certificate for '$dns'..." -ForegroundColor Yellow 48 | 49 | $cert = New-SelfSignedCertificate ` 50 | -DnsName $dns, "127.0.0.1" ` 51 | -FriendlyName $friendlyName ` 52 | -CertStoreLocation "Cert:\$storeLocationMy\$storeNameMy" ` 53 | -KeyExportPolicy Exportable ` 54 | -NotAfter (Get-Date).AddYears(5) 55 | 56 | Write-Host "✔ Certificate created successfully!" -ForegroundColor Green 57 | } 58 | 59 | $myStore.Close() 60 | 61 | # --------------------------------------------- 62 | # Step 2 — Ensure certificate is trusted 63 | # --------------------------------------------- 64 | Write-Host "" 65 | Write-Host "🔐 Ensuring certificate is trusted..." -ForegroundColor Cyan 66 | 67 | $rootStore = New-Object System.Security.Cryptography.X509Certificates.X509Store($storeNameRoot, $storeLocationRoot) 68 | $rootStore.Open("ReadWrite") 69 | 70 | $alreadyInRoot = $rootStore.Certificates | 71 | Where-Object { $_.Thumbprint -eq $cert.Thumbprint } 72 | 73 | if ($alreadyInRoot) { 74 | Write-Host "✔ Certificate already trusted (Root store)." -ForegroundColor Green 75 | } 76 | else { 77 | Write-Host "⏳ Adding certificate to Trusted Root..." -ForegroundColor Yellow 78 | $rootStore.Add($cert) 79 | Write-Host "✔ Certificate trusted successfully!" -ForegroundColor Green 80 | } 81 | 82 | $rootStore.Close() 83 | 84 | # --------------------------------------------- 85 | # Step 3 — Clean old HTTPS bindings 86 | # --------------------------------------------- 87 | Write-Host "" 88 | Write-Host "🧹 Cleaning old HTTPS bindings on port $port..." -ForegroundColor Cyan 89 | 90 | try { 91 | netsh http delete sslcert ipport=0.0.0.0:$port | Out-Null 92 | Write-Host "✔ Old bindings removed." -ForegroundColor Green 93 | } 94 | catch { 95 | Write-Host "ℹ No old bindings found." -ForegroundColor DarkGray 96 | } 97 | 98 | # --------------------------------------------- 99 | # Step 4 — Bind certificate to port 100 | # --------------------------------------------- 101 | Write-Host "" 102 | Write-Host "🔗 Binding certificate to port $port..." -ForegroundColor Cyan 103 | 104 | $thumb = $cert.Thumbprint 105 | $appid = [guid]::NewGuid() 106 | 107 | netsh http add sslcert ipport=0.0.0.0:$port certhash=$thumb certstorename=$storeNameMy appid="{$appid}" | Out-Null 108 | 109 | Write-Host "✔ HTTPS binding added successfully!" -ForegroundColor Green 110 | 111 | # --------------------------------------------- 112 | # Step 5 — Summary 113 | # --------------------------------------------- 114 | Write-Host "" 115 | Write-Host "==============================================" 116 | Write-Host " SETUP COMPLETE 🎉" 117 | Write-Host "==============================================" 118 | Write-Host "" 119 | Write-Host "🔒 HTTPS is now enabled for your local server." 120 | Write-Host "" 121 | Write-Host "📜 Details:" 122 | Write-Host " - Hostname: $dns" 123 | Write-Host " - Port: $port" 124 | Write-Host " - Prefix: $prefix" 125 | Write-Host " - Thumbprint: $thumb" 126 | Write-Host " - Cert Name: $friendlyName" 127 | Write-Host "" 128 | Write-Host "🧪 Test it in your browser:" 129 | Write-Host " $prefix" -ForegroundColor Yellow 130 | Write-Host "" 131 | Write-Host "✔ Your Chrome extension should now work without certificate errors." 132 | Write-Host "" 133 | Write-Host "==============================================" 134 | Write-Host "" 135 | --------------------------------------------------------------------------------