[misc] refine windows 10 scripts

This commit is contained in:
Klesh Wong 2021-01-13 23:20:59 +08:00
parent 266f6aff8f
commit c7a50e65bf
17 changed files with 329 additions and 475 deletions

27
win/bin/bdiso-to-mkv.ps1 Normal file
View File

@ -0,0 +1,27 @@
param (
[parameter(Mandatory=$false)] [switch] $Delete,
[parameter(Mandatory=$false)] [string] $OutFormat=".mkv",
[parameter(Mandatory=$true, Position=0)] [string] $InPath,
[parameter(Mandatory=$true, Position=1)] [string] $OutPath
)
if (-not (Test-Path -LiteralPath $InPath -Type Leaf)) {
Write-Error "Invalid Input File Path $($InPath)"
exit
}
if (-not (Test-Path -LiteralPath $OutPath)) {
Write-Error "Invalid Output Path $($OutPath)"
exit
}
if (Test-Path -LiteralPath $OutPath -PathType Container) {
$OutPath = Join-Path $OutPath ((Split-Path -Leaf $InPath) + $OutFormat)
}
$ConvertedInPath = Convert-Path -LiteralPath $InPath
$InDrive = "bluray:$((Mount-DiskImage $ConvertedInPath | Get-Volume).DriveLetter):\\"
ffmpeg.exe -i $InDrive -c:v copy $OutPath
Dismount-DiskImage $ConvertedInPath
if ($Delete) {
Remove-Item -LiteralPath $InPath
}

View File

@ -0,0 +1 @@
Remove-Item $env:AppData\Microsoft\Windows\Recent\* -Recurse

View File

@ -1,25 +1,25 @@
[CmdletBinding()] [CmdletBinding()]
param ( param (
[Parameter()] [Parameter()]
[string] [string]
$FontPath $FontPath
) )
Add-Type -AssemblyName PresentationCore Add-Type -AssemblyName PresentationCore
$face = New-Object System.Windows.Media.GlyphTypeface -ArgumentList "$(Resolve-Path $FontPath)" $face = New-Object System.Windows.Media.GlyphTypeface -ArgumentList "$(Resolve-Path $FontPath)"
$style = "$($face.Style)" $style = "$($face.Style)"
$weight = "$($face.Weight)" $weight = "$($face.Weight)"
$stretch = "$($face.Stretch)" $stretch = "$($face.Stretch)"
$name = $face.FamilyNames["en-US"] -replace '\W','' $name = $face.FamilyNames["en-US"] -replace '\W',''
if ($style -ne "Normal") { if ($style -ne "Normal") {
$name += "-$($style)" $name += "-$($style)"
} }
if ($weight -ne "Normal") { if ($weight -ne "Normal") {
$name += "-$($weight)" $name += "-$($weight)"
} }
if ($stretch -ne "Normal") { if ($stretch -ne "Normal") {
$name += "-$(stretch)" $name += "-$(stretch)"
} }
$name $name

2
win/bin/list-fonts.ps1 Normal file
View File

@ -0,0 +1,2 @@
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
(New-Object System.Drawing.Text.InstalledFontCollection).Families

View File

@ -1,202 +1,202 @@
[CmdletBinding()] [CmdletBinding()]
param ( param (
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$ApiKey='18224187-6d4fdb0c31aebbab0f814ab5d', $ApiKey='18224187-6d4fdb0c31aebbab0f814ab5d',
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$Keyword, $Keyword,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$Id, $Id,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[ValidateSet('all', 'photo', 'illustration', 'vector')] [ValidateSet('all', 'photo', 'illustration', 'vector')]
[string] [string]
$Type, $Type,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[ValidateSet('all', 'horizontal', 'vertical')] [ValidateSet('all', 'horizontal', 'vertical')]
[string] [string]
$Orientation, $Orientation,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[ValidateSet( [ValidateSet(
'backgrounds', 'backgrounds',
'fashion', 'fashion',
'nature', 'nature',
'science', 'science',
'education', 'education',
'feelings', 'feelings',
'health', 'health',
'people', 'people',
'religion', 'religion',
'places', 'places',
'animals', 'animals',
'industry', 'industry',
'computer', 'computer',
'food', 'food',
'sports', 'sports',
'transportation', 'transportation',
'travel', 'travel',
'buildings', 'buildings',
'business', 'business',
'music' 'music'
)] )]
[string] [string]
$Category, $Category,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[int] [int]
$MinWidth=0, $MinWidth=0,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[int] [int]
$MinHeight=0, $MinHeight=0,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[ValidateSet( [ValidateSet(
"grayscale", "grayscale",
"transparent", "transparent",
"red", "red",
"orange", "orange",
"yellow", "yellow",
"green", "green",
"turquoise", "turquoise",
"blue", "blue",
"lilac", "lilac",
"pink", "pink",
"white", "white",
"gray", "gray",
"black", "black",
"brown" "brown"
)] )]
[string[]] [string[]]
$Colors, $Colors,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[bool] [bool]
$EditorsChoiceOnly=$false, $EditorsChoiceOnly=$false,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[bool] [bool]
$SafeForWorkOnly=$false, $SafeForWorkOnly=$false,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[ValidateSet("popular", "latest")] [ValidateSet("popular", "latest")]
[string] [string]
$Order='popular', $Order='popular',
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[int] [int]
$Page=1, $Page=1,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[ValidateRange(3, 200)] [ValidateRange(3, 200)]
[int] [int]
$Size=50, $Size=50,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$OutFile, $OutFile,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$OutDir, $OutDir,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[bool] [bool]
$OutDirWithType=$true $OutDirWithType=$true
) )
if ($OutDir -and -not $OutFile) { if ($OutDir -and -not $OutFile) {
$OutFile $OutFile
} }
function Save-Hit { function Save-Hit {
param ( param (
[Parameter()] [Parameter()]
[PSCustomObject] [PSCustomObject]
$hit $hit
) )
$FilePath = $OutFile $FilePath = $OutFile
if (-not $FilePath) { if (-not $FilePath) {
$FilePath = $OutDir $FilePath = $OutDir
if ($OutDirWithType) { if ($OutDirWithType) {
$FilePath = Join-Path $FilePath ($hit.type -replace '\W+','_' ) $FilePath = Join-Path $FilePath ($hit.type -replace '\W+','_' )
} }
if (-not (Test-Path $FilePath)) { if (-not (Test-Path $FilePath)) {
New-Item -ItemType Directory $FilePath | Out-Null New-Item -ItemType Directory $FilePath | Out-Null
} }
$FileName = ($hit.id.ToString() + '_' + $FileName = ($hit.id.ToString() + '_' +
($hit.tags -split ", " | %{ $_ -replace '\s+','-' } | Join-String -Separator '_') + ($hit.tags -split ", " | %{ $_ -replace '\s+','-' } | Join-String -Separator '_') +
'.' + $hit.largeImageURL.Split('.')[-1]) '.' + $hit.largeImageURL.Split('.')[-1])
$FilePath = Join-Path $FilePath $FileName $FilePath = Join-Path $FilePath $FileName
} }
$msg = "saving $($hit.id) to $FilePath" $msg = "saving $($hit.id) to $FilePath"
Write-Host $msg.PadRight(100) -NoNewline Write-Host $msg.PadRight(100) -NoNewline
if (Test-Path $FilePath) { if (Test-Path $FilePath) {
Write-Host "[SKIP]" Write-Host "[SKIP]"
} else { } else {
$job = Start-Job -ScriptBlock { $job = Start-Job -ScriptBlock {
try { try {
Invoke-WebRequest -TimeoutSec 5 -Uri $args[0] -OutFile $args[1] Invoke-WebRequest -TimeoutSec 5 -Uri $args[0] -OutFile $args[1]
$true $true
} catch { } catch {
$false $false
} }
} -ArgumentList $hit.largeImageURL,$FilePath } -ArgumentList $hit.largeImageURL,$FilePath
$fg = 'red' $fg = 'red'
$tx = '[TIMEOUTED]' $tx = '[TIMEOUTED]'
if (Wait-Job $job -Timeout 20) { if (Wait-Job $job -Timeout 20) {
$ok = Receive-Job $job $ok = Receive-Job $job
$fg = $ok ? 'green' : 'red' $fg = $ok ? 'green' : 'red'
$tx = $ok ? '[OK]' : '[Failed]' $tx = $ok ? '[OK]' : '[Failed]'
} }
Remove-Job -force $job Remove-Job -force $job
Write-Host -ForegroundColor $fg $tx Write-Host -ForegroundColor $fg $tx
} }
} }
[System.Net.ServicePointManager]::MaxServicePointIdleTime = 5 [System.Net.ServicePointManager]::MaxServicePointIdleTime = 5
$Res = Invoke-WebRequest -TimeoutSec 5 -Uri https://pixabay.com/api/ -Body @{ $Res = Invoke-WebRequest -TimeoutSec 5 -Uri https://pixabay.com/api/ -Body @{
key = $ApiKey; key = $ApiKey;
q = $Keyword; q = $Keyword;
id = $Id; id = $Id;
image_type = $Type; image_type = $Type;
orientation = $Orientation; orientation = $Orientation;
category = $Category; category = $Category;
min_width = $MinWidth; min_width = $MinWidth;
min_height = $MinHeight; min_height = $MinHeight;
colors = $Colors; colors = $Colors;
editors_choice = $EditorsChoiceOnly; editors_choice = $EditorsChoiceOnly;
safesearch = $SafeForWorkOnly; safesearch = $SafeForWorkOnly;
order = $Order; order = $Order;
page = $Page; page = $Page;
per_page = $Size; per_page = $Size;
} | ConvertFrom-Json } | ConvertFrom-Json
Write-Host "Total $($res.total) Accessible $($res.totalHits)" Write-Host "Total $($res.total) Accessible $($res.totalHits)"
$Listing = -not $OutFile -and -not $OutDir $Listing = -not $OutFile -and -not $OutDir
if ($Res.hits.Length -eq 1) { if ($Res.hits.Length -eq 1) {
if ($Listing) { if ($Listing) {
$Res.hits[0] $Res.hits[0]
} else { } else {
Save-Hit $Res.hits[0] Save-Hit $Res.hits[0]
} }
} else { } else {
if ($Listing) { if ($Listing) {
$Res.hits | Select-Object -Property id,type,largeImageURL | Format-Table $Res.hits | Select-Object -Property id,type,largeImageURL | Format-Table
} else { } else {
$Res.hits | %{ Save-Hit $_ } $Res.hits | %{ Save-Hit $_ }
# Save-Hit $Res.hits[0] # Save-Hit $Res.hits[0]
} }
} }

View File

@ -1,56 +1,56 @@
[CmdletBinding()] [CmdletBinding()]
param ( param (
[ValidateSet("Projects", "MarkRead")] [ValidateSet("Projects", "MarkRead")]
[string] [string]
$CMD, $CMD,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$PRO, $PRO,
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$ORG="malong", $ORG="malong",
[Parameter(Mandatory=$false)] [Parameter(Mandatory=$false)]
[string] [string]
$TOKEN="4ef37b6c118e44a499450fb996f2d58ef81faa46e2f14f38aadfa6d4ee0c4062" $TOKEN="4ef37b6c118e44a499450fb996f2d58ef81faa46e2f14f38aadfa6d4ee0c4062"
) )
function Projects { function Projects {
$PROJECTS_URL="https://sentry.malongtech.cn/api/0/projects/" $PROJECTS_URL="https://sentry.malongtech.cn/api/0/projects/"
while ($PROJECTS_URL) { while ($PROJECTS_URL) {
$projectsRes = Invoke-WebRequest -Uri $PROJECTS_URL -Headers @{'Authorization'="Bearer $TOKEN"} $projectsRes = Invoke-WebRequest -Uri $PROJECTS_URL -Headers @{'Authorization'="Bearer $TOKEN"}
$projects = $projectsRes.Content | ConvertFrom-Json $projects = $projectsRes.Content | ConvertFrom-Json
if (-not $projects.Length) { if (-not $projects.Length) {
break break
} }
foreach ($project in $projects) { foreach ($project in $projects) {
Write-Host $project.id $project.name Write-Host $project.id $project.name
} }
$PROJECTS_URL=$projectsRes.Headers.Link $PROJECTS_URL=$projectsRes.Headers.Link
if (-not $PROJECTS_URL.Length) { if (-not $PROJECTS_URL.Length) {
break break
} }
$PROJECTS_URL = $PROJECTS_URL[0].ToString() $PROJECTS_URL = $PROJECTS_URL[0].ToString()
$PROJECTS_URL=$PROJECTS_URL.SubString(1, $PROJECTS_URL.IndexOf(";")-2) $PROJECTS_URL=$PROJECTS_URL.SubString(1, $PROJECTS_URL.IndexOf(";")-2)
} }
} }
function MarkRead { function MarkRead {
$ISSUES_URL="https://sentry.malongtech.cn/api/0/projects/$ORG/$PRO/issues/" $ISSUES_URL="https://sentry.malongtech.cn/api/0/projects/$ORG/$PRO/issues/"
while ($true) { while ($true) {
$issuesRes = Invoke-WebRequest -Uri $ISSUES_URL -Headers @{'Authorization'="Bearer $TOKEN"} $issuesRes = Invoke-WebRequest -Uri $ISSUES_URL -Headers @{'Authorization'="Bearer $TOKEN"}
$issues = $issuesRes.Content | ConvertFrom-Json $issues = $issuesRes.Content | ConvertFrom-Json
if (-not $issues.Length) { if (-not $issues.Length) {
break break
} }
$qs = $issues | Select-Object -Property id | %{"id=$($_.id)"} | Join-String -Separator "&" $qs = $issues | Select-Object -Property id | %{"id=$($_.id)"} | Join-String -Separator "&"
$deleteRes = Invoke-WebRequest -Uri "$($ISSUES_URL)?$qs" -Method Delete -Body @{'id'=$ids} -Headers @{'Authorization'="Bearer $TOKEN"} $deleteRes = Invoke-WebRequest -Uri "$($ISSUES_URL)?$qs" -Method Delete -Body @{'id'=$ids} -Headers @{'Authorization'="Bearer $TOKEN"}
Write-Host "status: $($deleteRes.StatusCode) content: $($deleteRes.Content)" Write-Host "status: $($deleteRes.StatusCode) content: $($deleteRes.Content)"
} }
} }
switch ($CMD) { switch ($CMD) {
"MarkRead" { MarkRead } "MarkRead" { MarkRead }
Default { Projects } Default { Projects }
} }

4
win/mpv.ps1 Normal file
View File

@ -0,0 +1,4 @@
$dotfiles=(Get-Item $PSScriptRoot).Parent.FullName
New-Item -ItemType SymbolicLink -Target $dotfiles\config\mpv\mpv.conf -Path $Env:APPDATA\mpv\mpv.conf -Force
New-Item -ItemType SymbolicLink -Target $dotfiles\config\mpv\scripts -Path $Env:APPDATA\mpv\scripts -Force

6
win/oh-my-posh.ps1 Normal file
View File

@ -0,0 +1,6 @@
# Install-Module -Name PowerShellGet -Force -AllowPrerelease
# Install-Module -Name posh-git
# Install-Module -Name oh-my-posh
$dotfiles=(Get-Item $PSScriptRoot).Parent.FullName
New-Item -ItemType SymbolicLink -Target $dotfiles\win\profile.ps1 -Path $profile -Force

View File

@ -1,32 +0,0 @@
# execute this first: Set-ExecutionPolicy RemoteSigned
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
# link config files
$dotfiles=(Get-Item $PSScriptRoot).Parent.FullName
New-Item -ItemType SymbolicLink -Target $dotfiles\win\profile.ps1 -Path $profile -Force
New-Item -ItemType SymbolicLink -Target $dotfiles\config\mpv\mpv.conf -Path $Env:APPDATA\mpv\mpv.conf -Force
New-Item -ItemType SymbolicLink -Target $dotfiles\config\mpv\scripts -Path $Env:APPDATA\mpv\scripts -Force
New-Item -ItemType SymbolicLink -Target $dotfiles\config\nvim -Path $Env:LOCALAPPDATA\nvim -Force
Remove-Item -Force -Recurse $Env:APPDATA\pip
New-Item -ItemType Directory -Path $Env:APPDATA\pip
New-Item -ItemType SymbolicLink -Target $dotfiles\pip\pip.conf -Path $Env:APPDATA\pip\pip.ini -Force
# fix Shift key toggling Cn/En fro MS wubi
#if (-not (Get-ScheduledTask -TaskName "Wubi No Shift")) {
#$wubiAction = New-ScheduledTaskAction -Execute 'Powershell.exe' `
#-Argument "-NoProfile -WindowStyle Hidden -File $PSScriptRoot\wubi-no-shift.ps1"
#$wubiTrigger = New-ScheduledTaskTrigger -AtLogOn
#Register-ScheduledTask -Action $wubiAction -Trigger $wubiTrigger -TaskName "Wubi No Shift" -Description "Disable Shift key toggling CN/EN" -RunLevel Highest
#}
Install-Module -Name PowerShellGet -Force -AllowPrerelease
Install-Module -Name posh-git
Install-Module -Name oh-my-posh
# replace notepad with nvim-qt
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v "Debugger" /t REG_SZ /d "${dotfiles}\win\npd.vbs" /f

7
win/vim.ps1 Normal file
View File

@ -0,0 +1,7 @@
$dotfiles=(Get-Item $PSScriptRoot).Parent.FullName
if ( ! (Test-Path $Env:LOCALAPPDATA\nvim) ) {
New-Item -ItemType Directory -Path $Env:LOCALAPPDATA\nvim
}
New-Item -Force -ItemType SymbolicLink -Target $dotfiles\cli\vim\init.vim -Path $Env:LOCALAPPDATA\nvim\init.vim
New-Item -Force -ItemType SymbolicLink -Target $dotfiles\cli\vim\coc-settings.json -Path $Env:LOCALAPPDATA\nvim\coc-settings.json

View File

@ -1,95 +0,0 @@
// This file was initially generated by Windows Terminal 1.0.1811.0
// It should still be usable in newer versions, but newer versions might have additional
// settings, help text, or changes that you will not see unless you clear this file
// and let us generate a new one for you.
// To view the default settings, hold "alt" while clicking on the "Settings" button.
// For documentation on these settings, see: https://aka.ms/terminal-documentation
{
"$schema": "https://aka.ms/terminal-profiles-schema",
"defaultProfile": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
// You can add more global application settings here.
// To learn more about global settings, visit https://aka.ms/terminal-global-settings
// If enabled, selections are automatically copied to your clipboard.
"copyOnSelect": true,
// If enabled, formatted data is also copied to your clipboard
"copyFormatting": false,
// A profile specifies a command to execute paired with information about how it should look and feel.
// Each one of them will appear in the 'New Tab' dropdown,
// and can be invoked from the commandline with `wt.exe -p xxx`
// To learn more about profiles, visit https://aka.ms/terminal-profile-settings
"profiles":
{
"defaults":
{
// Put settings here that you want to apply to all profiles.
"acrylicOpacity" : 0.90,
"colorScheme": "One Half Dark",
"fontFace" : "Hurmit NF",
"useAcrylic" : true
},
"list":
[
{
// Make changes here to the powershell.exe profile.
"guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"name": "Windows PowerShell",
"commandline": "powershell.exe",
"hidden": false
},
{
// Make changes here to the cmd.exe profile.
"guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
"name": "命令提示符",
"commandline": "cmd.exe",
"hidden": false
},
{
"guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}",
"hidden": false,
"name": "Azure Cloud Shell",
"source": "Windows.Terminal.Azure"
},
{
"guid": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
"hidden": false,
"name": "PowerShell",
"source": "Windows.Terminal.PowershellCore"
}
]
},
// Add custom color schemes to this array.
// To learn more about color schemes, visit https://aka.ms/terminal-color-schemes
"schemes": [],
// Add custom keybindings to this array.
// To unbind a key combination from your defaults.json, set the command to "unbound".
// To learn more about keybindings, visit https://aka.ms/terminal-keybindings
"keybindings":
[
// Copy and paste are bound to Ctrl+Shift+C and Ctrl+Shift+V in your defaults.json.
// These two lines additionally bind them to Ctrl+C and Ctrl+V.
// To learn more about selection, visit https://aka.ms/terminal-selection
{ "command": {"action": "copy", "singleLine": false }, "keys": "ctrl+c" },
{ "command": "paste", "keys": "ctrl+v" },
// Press Ctrl+Shift+F to open the search box
{ "command": "find", "keys": "ctrl+shift+f" },
// Press Alt+Shift+D to open a new pane.
// - "split": "auto" makes this pane open in the direction that provides the most surface area.
// - "splitMode": "duplicate" makes the new pane use the focused pane's profile.
// To learn more about panes, visit https://aka.ms/terminal-panes
{ "command": { "action": "splitPane", "split": "auto", "splitMode": "duplicate" }, "keys": "alt+shift+d" },
{ "command": "scrollUp", "keys": "pgup" },
{ "command": "scrollDown", "keys": "pgdn" },
{ "command": "prevTab", "keys": "ctrl+pgup" },
{ "command": "nextTab", "keys": "ctrl+pgdn" }
]
}

View File

@ -1,4 +0,0 @@
if [ -t 1 ]; then
exec /usr/bin/fish
fi

View File

@ -1,62 +0,0 @@
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
Function ExitOnError ([string]$message) {
Write-Error $message
Read-Host -Prompt "Press Enter to continue"
exit -1
}
$Supported = @{
"B3448BF077665F2E1CA67094BCF2A7C5" = 0x14DE1;
"DE5FA392A825332AB3E348EF0316B514" = 0x16A61;
"F653C99D4A0C61D4B2C64358B8213BD8" = 0x15C11;
"C8BC76C87563E78C9BC85EE9F4F96760" = 0x15C11;
}
$ChsIME = "ChsIME"
$ChsIMEExe = "${ChsIME}.exe"
# make sure CheIme.exe is the right version
$ChsImeExePath = "$env:windir\System32\InputMethod\CHS\$ChsIMEExe"
$ChsIMEHash = (Get-FileHash $ChsImeExePath -Algorithm MD5).Hash
$offsetAddr = $Supported[$ChsIMEHash]
if (-not $offsetAddr) {
ExitOnError 'Unsupported ChsIme.exe'
}
Add-Type -MemberDefinition @'
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
Int32 nSize,
out IntPtr lpNumberOfBytesWritten);
'@ -Name Kernel32 -Namespace Pinvoke
$i = 0
while ($i++ -lt 30) {
$ps = Get-Process -Name $ChsIME
foreach ($p in $ps) {
$hModule = $p.Modules | Where-Object {$_.ModuleName -eq $ChsIMEExe}
if (!$hModule) {
continue
}
$hModule = $hModule[0]
$addr = [IntPtr]::Add($hModule.BaseAddress, $offsetAddr)
[Int32]$n = 0
$pidd = $p.id
if ([Pinvoke.Kernel32]::WriteProcessMemory($p.Handle[0], $addr, @(0x31, 0xc0), 2, [ref]$n)) {
Write-Output "$pidd is patched"
} else {
ExitOnError "Failed to patch $pidd"
}
}
if ($ps) {
break
}
Start-Sleep -Milliseconds 100
}