Universal.psm1

Import-Module "$PSScriptRoot\Universal.Cmdlets.dll"
[UniversalAutomation.AssemblyResolver]::Bind()
function Resolve-Variable {
    [CmdletBinding()]
    param($Name)

    $PSCmdlet.GetVariableValue($Name)
}

function Start-PSUServer {
    param(
        [Parameter()]
        $ExecutablePath = "Universal.Server.exe",
        [Parameter()]
        $ListenAddress
    )

    $Command = Get-Command $ExecutablePath -ErrorAction SilentlyContinue
    if ($null -eq $Command)
    {
        throw 'Unable to locate the Universal Server executable. You can use Install-PSUServer to download the latest version. Use the -UpdatePathVariable parameter to add the installation directory the the PATH.'
    }

    if ($ListenAddress)
    {
        $Env:Kestrel__Endpoints__HTTP__Url = $ListenAddress
    }

    Start-Process -FilePath $ExecutablePath 
}

function Install-PSUServer {
    param(
        [string]$Path
    )

    $platform = "win-x64";
    if ($PSVersionTable.Edition -eq 'Core')
    {
        if ($IsLinux)
        {
            $platform = "linux-x64"
        }
        else 
        {
            $platform = "osx-x64"
        }
    }

    if (-not $Path) {
        $Path = Join-Path $Env:ProgramData "PowerShellUniversal"
    }

    $Version = (Invoke-WebRequest https://imsreleases.blob.core.windows.net/universal/production/version.txt).Content
    Invoke-WebRequest "https://imsreleases.blob.core.windows.net/universal/production/$version/Universal.$platform.$Version.zip" -OutFile ".\Universal.$version.$platform.zip"
    Expand-Archive -Path ".\Universal.$Version.$platform.zip" -DestinationPath $Path -Force
    Remove-Item ".\Universal.$Version.$platform.zip" -Force

    $Scope = 'User'
    if ($platform -eq 'win-x64' -and ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    {
        $Scope = 'Machine'
    }

    $envPath = [Environment]::GetEnvironmentVariable('PATH', $Scope)
    $newpath = $envPath + ";" + $Path
    [Environment]::SetEnvironmentVariable("PATH", $newpath, $Scope)

    $Env:Path += ";" + $newpath
}