ProxyCommand.psm1

Set-StrictMode -Version 3

$GUID = "f482a1af-fdd3-4548-9b56-58149d54ce21"
$PROXY_COMMAND = "$PSScriptRoot\ProxyCommand.exe"

function Set-ProxyCommand {
  param(
    [string]$Proxy,
    [string]$Target,
    [string]$Prepend,
    [bool]$Async = $false
  )

  if ($Target -match "\.exe$") {
    Set-ProxyExecutable $Proxy $Target $Prepend $Async
  }
  elseif ($Target -match "\.bat$") {
    Set-ProxyBatchFile $Proxy $Target $Prepend
  }
}

function Set-ProxyExecutable {
  param(
    [string]$Proxy,
    [string]$Target,
    [string]$Prepend,
    [bool]$Async
  )

  if ([IO.Directory]::Exists($Proxy)) {
    $Proxy = Join-Path $Proxy (Split-Path -Leaf $Target)
  }

  Write-Verbose "$Proxy=$Target"

  Copy-Item $PROXY_COMMAND $Proxy -Force
  $Target | Set-Content -Encoding Unicode -LiteralPath $Proxy -Stream TargetPath

  if (![string]::IsNullOrEmpty($Prepend)) {
    $Prepend | Set-Content -Encoding Unicode -LiteralPath $Proxy -Stream Prepend
  }

  if ($Async) {
    "true" | Set-Content -Encoding Unicode -LiteralPath $Proxy -Stream Async
  }
}

function Set-ProxyBatchFile {
  param(
    [string]$Proxy,
    [string]$Target,
    [string]$Prepend
  )

  if ([IO.Directory]::Exists($Proxy)) {
    $Proxy = Join-Path $Proxy (Split-Path -Leaf $Target)
  }

  Write-Verbose "$Proxy=$Target"

  $template = @"
@echo off
rem generated by New-ProxyCommand on $((Get-Date).ToString("yyyy/MM/dd HH:mm:ss"))
rem nugetid: $GUID
rem target: $Target
rem prepend: $Prepend
"$Target" $Prepend %*
"@


  $template | Set-Content -Encoding default -LiteralPath $Proxy
}

function Test-Stream {
  param(
    [string]$Path,
    [string]$StreamName
  )

  try {
    $null = Get-Content -LiteralPath $Path -Stream $StreamName
    return $true
  }
  catch {
    return $false
  }
}

<#
.SYNOPSIS
Creates a proxy command to call a target program.
 
.DESCRIPTION
A proxy command is a small program that calls another program as a child process. It can be used as a shortcut in the command line environment.
 
.PARAMETER ProxyPath
A directory or name of a proxy command. If a directory is specified, the name of a proxy command is the same as the target program.
 
.PARAMETER TargetPath
A target program. A path of a target program. If it is a file, it should be an executable (`.exe`) or a batch file (`.bat`). If a directory is given, the cmdlet looks for executables and batch files in it and creates proxy commands for all executables and batch files found. This parameter can be given from the pipeline.
 
.PARAMETER Prepend
When specified, this value is given as additional arguments to the target program.
 
.PARAMETER Async
When specified, a proxy command doesn't wait for the target program to exit. This option is suitable for GUI applications.
 
.LINK
https://github.com/horker/proxycommand
https://www.powershellgallery.com/packages/ProxyCommand
#>

function New-ProxyCommand {
  [CmdletBinding()]
  param(
    [Parameter(Position=0, Mandatory=$true)]
    [string]$ProxyPath,

    [Parameter(Position=1, ValueFromPipeline=$true, Mandatory=$true)]
    [object]$TargetPath,

    [Parameter(Position=2, Mandatory=$false)]
    [string]$Prepend = "",

    [Parameter(Position=3, Mandatory=$false)]
    [switch]$Async = $false
  )

  begin {
    $ProxyPath = try { Resolve-Path $ProxyPath -EA Stop } catch { $_.TargetObject }
  }

  process {
    if ($TargetPath -is [IO.FileInfo] -or $TargetPath -is [IO.DirectoryInfo]) {
      $TargetPath = $TargetPath.FullName
    }
    if ([IO.Directory]::Exists($TargetPath)) {
      Get-ChildItem $TargetPath |
      Where-Object { $_.Extension -match "\.(exe|bat)$" } |
      ForEach-Object {
        Set-ProxyCommand $ProxyPath $_.FullName $Prepend $Async
      }
    }
    else {
      Set-ProxyCommand $ProxyPath $TargetPath $Prepend $Async
    }
  }
}

<#
.SYNOPSIS
Shows information on proxy commands.
 
.DESCRIPTION
Shows information on proxy commands.
 
.PARAMETER Path
A directory or name of proxy commands.
#>

function Show-ProxyCommand {
  [CmdletBinding()]
  param(
    [Parameter(Position=0, Mandatory=$true)]
    [string[]]$Path
  )

  foreach ($p in $Path) {
    $files = Get-ChildItem $p | where { $_.Extension -match "\.(exe|bat)$" }
    foreach ($f in $files) {
      if ($f.Extension -match "\.exe$") {
        if (Test-Stream $f.FullName "TargetPath") {
          $t = Get-Content $f.FullName -Stream "TargetPath"

          $a = Test-Stream $f.FullName "Async"

          $pre = $null
          if (Test-Stream $f.FullName "Prepend") {
            $pre = Get-Content $f.FullName -Stream "Prepend"
          }

          [PSCustomObject]@{
            Name = $f
            TargetPath = $t
            Async = $a
            Prepend = $pre
          }
        }
      }
      else {
        $contents = Get-Content -Total 5 $f.FullName
        try {
          if ($contents[2] -match $GUID) {
            $target = ([regex]'^rem target: (.+)$').Match($contents[3])
            $prepend = ([regex]'^rem prepend: (.+)$').Match($contents[4])
            [PSCustomObject]@{
              Name = $f
              TargetPath = $target.Groups[1].Value
              Async = $false
              Prepend = $prepend.Groups[1].Value
            }
          }
          elseif ($contents[1] -match $GUID) {
            # Old format (for compatibility)
            $target = ([regex]'^"([^"]+)"').Match($contents[3])
            [PSCustomObject]@{
              Name = $f.Name
              TargetPath = $target.Groups[1].Value
              Async = $false
              Prepend = $null
            }
          }
        }
        catch {
          # Skip unknown batch files
        }
      }
    }
  }
}