ProxyCommand.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
        }
      }
    }
  }
}