param( [Parameter(Mandatory=$true)][string]$Directory, [Parameter(Mandatory=$true)][string]$Output ) Add-Type -AssemblyName System.Runtime.WindowsRuntime [Windows.Storage.StorageFile, Windows.Storage, ContentType=WindowsRuntime] | Out-Null [Windows.Graphics.Imaging.BitmapDecoder, Windows.Graphics.Imaging, ContentType=WindowsRuntime] | Out-Null [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType=WindowsRuntime] | Out-Null [Windows.Globalization.Language, Windows.Globalization, ContentType=WindowsRuntime] | Out-Null function Await-Result($AsyncOperation, [Type]$ResultType) { $method = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.IsGenericMethod -and $_.GetParameters().Count -eq 1 } | Select-Object -First 1 $task = $method.MakeGenericMethod($ResultType).Invoke($null, @($AsyncOperation)) $task.Wait() return $task.Result } $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage([Windows.Globalization.Language]::new('ar-SA')) $rows = @() foreach ($item in Get-ChildItem -LiteralPath $Directory -Filter '*.png' -File | Sort-Object Name) { try { $file = Await-Result ([Windows.Storage.StorageFile]::GetFileFromPathAsync($item.FullName)) ([Windows.Storage.StorageFile]) $stream = Await-Result ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream]) $decoder = Await-Result ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder]) $bitmap = Await-Result ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap]) $result = Await-Result ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult]) $rows += [pscustomobject]@{file=$item.Name; text=(($result.Lines | ForEach-Object {$_.Text}) -join ' | ')} $stream.Dispose() } catch { $rows += [pscustomobject]@{file=$item.Name; text=''; error=$_.Exception.Message} } } $rows | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath $Output -Encoding UTF8 Write-Output ("OCR rows: " + $rows.Count)