Private/Invoke-WindowsPowerShell.ps1

function Invoke-WindowsPowerShell {
    <#
    .SYNOPSIS
    Executes a PowerShell script in Windows PowerShell using -File.

    .DESCRIPTION
    Invokes powershell.exe with -File and forwards provided script parameters.

    .PARAMETER ScriptPath
    Path to the script file to execute inside Windows PowerShell.

    .PARAMETER ScriptParameters
    Hashtable of parameters to pass to the script.

    .OUTPUTS
    System.Object[]
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$ScriptPath,

        [Parameter()]
        [hashtable]$ScriptParameters = @{}
    )

    $isWindowsHost = [System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT
    if (-not $isWindowsHost) {
        throw 'Windows PowerShell bridge is only supported on Windows.'
    }

    if (-not (Test-Path -LiteralPath $ScriptPath)) {
        throw "Script file was not found: $ScriptPath"
    }

    $windowsPowerShell = (Get-Command powershell.exe -ErrorAction Stop).Source

    $argumentList = @(
        '-NoLogo'
        '-NoProfile'
        '-NonInteractive'
        '-ExecutionPolicy'
        'Bypass'
        '-File'
        $ScriptPath
    )

    foreach ($entry in $ScriptParameters.GetEnumerator()) {
        $name = [string]$entry.Key
        $value = $entry.Value

        if ([string]::IsNullOrWhiteSpace($name)) {
            continue
        }

        if ($null -eq $value) {
            continue
        }

        $argumentList += "-$name"
        $argumentList += [string]$value
    }

    $output = & $windowsPowerShell @argumentList 2>&1

    if ($LASTEXITCODE -ne 0) {
        $details = ($output | Out-String).Trim()
        throw "Failed to execute script in Windows PowerShell. $details"
    }

    return $output
}