PowerShell/Scripts/translate-file.ps1
2023-06-30 22:18:13 +02:00

49 lines
1.8 KiB
PowerShell
Executable File

<#
.SYNOPSIS
Translates a text file into another language
.DESCRIPTION
This PowerShell script translates a text file into another language.
.PARAMETER File
Specifies the file to translate
.PARAMETER SourceLang
Specifies the source language
.PARAMETER TargetLang
Specifies the target language
.EXAMPLE
PS> ./translate-file C:\Memo.txt en de
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$File = "", [string]$SourceLang = "", [string]$TargetLang = "")
function UseLibreTranslate { param([string]$Text, [string]$SourceLang, [string]$TargetLang)
$Parameters = @{"q"="$Text"; "source"="$SourceLang"; "target"="$TargetLang"; }
$Result = (Invoke-WebRequest -Uri https://libretranslate.de/translate -Method POST -Body ($Parameters|ConvertTo-Json) -ContentType "application/json" -useBasicParsing).content | ConvertFrom-Json
Start-Sleep -seconds 6 # 10 requests per minute maximum
return $Result.translatedText
}
try {
if ($File -eq "" ) { $File = Read-Host "Enter path to file" }
if ($SourceLang -eq "" ) { $SourceLang = Read-Host "Enter language used in this file" }
if ($TargetLang -eq "" ) { $TargetLang = Read-Host "Enter language to translate to" }
$Lines = Get-Content -path $File
foreach($Line in $Lines) {
if ("$Line" -eq "") { Write-Output "$Line"; continue }
if ("$Line" -eq " ") { Write-Output "$Line"; continue }
if ("$Line" -like "===*") { Write-Output "$Line"; continue }
if ("$Line" -like "---*") { Write-Output "$Line"; continue }
if ("$Line" -like "!*(/*)") { Write-Output "$Line"; continue }
$Result = UseLibreTranslate $Line $SourceLang $TargetLang
Write-Output $Result
}
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}