param( [Parameter(Mandatory = $true)] [string]$ImagePath ) $ErrorActionPreference = "Stop" Add-Type -AssemblyName System.Runtime.WindowsRuntime [Windows.Storage.StorageFile,Windows.Storage,ContentType=WindowsRuntime] | Out-Null [Windows.Storage.FileAccessMode,Windows.Storage,ContentType=WindowsRuntime] | Out-Null [Windows.Storage.Streams.IRandomAccessStream,Windows.Storage.Streams,ContentType=WindowsRuntime] | Out-Null [Windows.Graphics.Imaging.BitmapDecoder,Windows.Graphics.Imaging,ContentType=WindowsRuntime] | Out-Null [Windows.Graphics.Imaging.SoftwareBitmap,Windows.Graphics.Imaging,ContentType=WindowsRuntime] | Out-Null [Windows.Media.Ocr.OcrEngine,Windows.Media.Ocr,ContentType=WindowsRuntime] | Out-Null function Await-Operation { param( [Parameter(Mandatory = $true)] [object]$Operation, [Parameter(Mandatory = $true)] [type]$ResultType ) $method = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq "AsTask" -and $_.IsGenericMethodDefinition -and $_.GetParameters().Count -eq 1 } | Select-Object -First 1 $task = $method.MakeGenericMethod($ResultType).Invoke($null, @($Operation)) return $task.GetAwaiter().GetResult() } if (-not (Test-Path -LiteralPath $ImagePath)) { throw "Image file does not exist: $ImagePath" } $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages() if ($null -eq $engine) { throw "Windows OCR is not available for the current user language. Install OCR language support or import Excel/CSV." } $file = Await-Operation ([Windows.Storage.StorageFile]::GetFileFromPathAsync($ImagePath)) ([Windows.Storage.StorageFile]) $stream = Await-Operation ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream]) $decoder = Await-Operation ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder]) $bitmap = Await-Operation ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap]) $result = Await-Operation ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult]) [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 Write-Output $result.Text