functions/common/Invoke-WithPowerShell.ps1

function Invoke-WithPowerShell {
    param (
        [Parameter(Mandatory = $true)]
        [string]$ScriptPath,

        [Parameter(Mandatory = $true)]
        [string]$ConfigPath,

        [Parameter(Mandatory = $true)]
        [ValidateSet(5, 7)]
        [int]$TargetVersion,

        [Parameter(Mandatory = $false)]
        [string]$LogFile
    )

    if (-not (Test-Path $ScriptPath)) {
        throw "Script '$ScriptPath' wurde nicht gefunden."
    }

    if (-not (Test-Path $ConfigPath)) {
        throw "Konfigurationsdatei '$ConfigPath' wurde nicht gefunden."
    }

    if ($TargetVersion -eq 7) {
        $pwshPath = "C:\Program Files\PowerShell\7\pwsh.exe"
        if (-not (Test-Path $pwshPath)) {
            throw "PowerShell 7 wurde nicht gefunden unter '$pwshPath'."
        }

        Write-Host "[$((Get-Date).ToString('HH:mm:ss'))] >> Starte '$ScriptPath' in PowerShell 7..."
        & $pwshPath -Command "& '$ScriptPath' -ConfigPath '$ConfigPath' -LogFile '$LogFile'"
    }
    elseif ($TargetVersion -eq 5) {
        $ps5Path = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
        if (-not (Test-Path $ps5Path)) {
            throw "PowerShell 5 wurde nicht gefunden unter '$ps5Path'."
        }

        Write-Host "[$((Get-Date).ToString('HH:mm:ss'))] >> Starte '$ScriptPath' in PowerShell 5..."
        & $ps5Path -Command "& '$ScriptPath' -ConfigPath '$ConfigPath' -LogFile '$LogFile'"
    }
}