-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.ps1
101 lines (82 loc) · 2.26 KB
/
command.ps1
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
class PwshRunCommand {
[object]$Cmd
[object[]]$Arguments
[string]$WorkDir
[string]$Runner
[boolean]$IsBlock = $false
PwshRunCommand([object] $cmd) {
$this.Cmd = $cmd
$this.IsBlock = $cmd -is [scriptblock]
}
[void] StartProcess([switch]$runAs) {
$processArgs = @{};
if ($runAs) {
$processArgs["Verb"] = "RunAs"
}
if ($this.WorkDir) {
$processArgs["WorkingDirectory"] = $this.WorkDir
}
$processArgs["ArgumentList"] = $this.Arguments
$processArgs["FilePath"] = $this.Cmd
& "Start-Process" @processArgs
}
[string] Serialize() {
$original = $this.Cmd
$this.Cmd = $original.ToString()
$result = ConvertTo-Json -Compress $this
$this.Cmd = $original
return $result
}
static [PwshRunCommand] Deserialize([string]$serialized) {
$obj = ConvertFrom-Json -AsHashtable $serialized
if ($obj.IsBlock) {
$obj.Cmd = [scriptblock]::Create($obj.Cmd)
}
return New-PwshRunCommand $obj.Cmd -Arguments $obj.Arguments -WorkDir $obj.WorkDir -Runner $obj.Runner
}
}
function New-PwshRunCommand {
param(
[Parameter(Position=0)]
[object]$cmd,
[object[]]$arguments = $null,
[string]$workDir = $null,
[string]$runner = $env:PWSHRUN_RUNNER
)
$command = [PwshRunCommand]::new($cmd)
$command.Arguments = $arguments
$command.WorkDir = $workDir
$command.Runner = $runner
return $command
}
function Invoke-PwshRunCommandInternal {
param(
[Parameter(Mandatory=$true)]
[PSObject] $command
)
if ($command.WorkDir) {
Push-Location $command.WorkDir
}
$a = $command.Arguments
& $command.Cmd @a
if ($this.WorkDir) {
Pop-Location
}
}
function Push-PwshRunCommand {
param(
[Parameter(Mandatory=$true)]
[PSObject] $command
)
$file = New-TemporaryFile
$command.Serialize() | Out-File $file.FullName
return $file.FullName
}
function Pop-PwshRunCommand {
param(
[string]$commandFile
)
$command = [PwshRunCommand]::Deserialize($(Get-Content $commandFile))
Remove-Item $commandFile
Invoke-PwshRunCommand $command
}