1
+ Add-Type - AssemblyName " System.Core"
2
+ Add-Type - TypeDefinition @"
3
+ public class ScriptException : System.Exception
4
+ {
5
+ public int ExitCode { get; private set; }
6
+ public ScriptException(string message, int exitCode) : base(message)
7
+ {
8
+ this.ExitCode = exitCode;
9
+ }
10
+ }
11
+ "@
12
+
13
+ New-Module - ScriptBlock {
14
+ $scriptsDirectory = $PSScriptRoot
15
+ Export-ModuleMember - Variable scriptsDirectory
16
+ }
17
+
18
+ New-Module - ScriptBlock {
19
+ function Die ([int ]$exitCode , [string ]$message , [object []]$output ) {
20
+ # $host.SetShouldExit($exitCode)
21
+ if ($output ) {
22
+ Write-Host $output
23
+ $message += " . See output above."
24
+ }
25
+ $hash = @ {
26
+ Message = $message
27
+ ExitCode = $exitCode
28
+ Output = $output
29
+ }
30
+ Throw (New-Object - TypeName ScriptException - ArgumentList $message , $exitCode )
31
+ # throw $message
32
+ }
33
+
34
+
35
+ function Run-Command ([scriptblock ]$Command , [switch ]$Fatal , [switch ]$Quiet ) {
36
+ $output = " "
37
+
38
+ $exitCode = 0
39
+
40
+ if ($Quiet ) {
41
+ $output = & $command 2>&1 | % { " $_ " }
42
+ } else {
43
+ & $command
44
+ }
45
+
46
+ if (! $? -and $LastExitCode -ne 0 ) {
47
+ $exitCode = $LastExitCode
48
+ } elseif ($? -and $LastExitCode -ne 0 ) {
49
+ $exitCode = $LastExitCode
50
+ }
51
+
52
+ if ($exitCode -ne 0 ) {
53
+ if (! $Fatal ) {
54
+ Write-Host " `` $Command `` failed" $output
55
+ } else {
56
+ Die $exitCode " `` $Command `` failed" $output
57
+ }
58
+ }
59
+ $output
60
+ }
61
+
62
+ function Run-Process ([int ]$Timeout , [string ]$Command , [string []]$Arguments , [switch ]$Fatal = $false )
63
+ {
64
+ $args = ($Arguments | % { " `" $_ `" " })
65
+ [object []] $output = " $Command " + $args
66
+ $exitCode = 0
67
+ $outputPath = [System.IO.Path ]::GetTempFileName()
68
+ $process = Start-Process - PassThru - NoNewWindow - RedirectStandardOutput $outputPath $Command ($args | % { " `" $_ `" " })
69
+ Wait-Process - InputObject $process - Timeout $Timeout - ErrorAction SilentlyContinue
70
+ if ($process.HasExited ) {
71
+ $output += Get-Content $outputPath
72
+ $exitCode = $process.ExitCode
73
+ } else {
74
+ $output += " Process timed out. Backtrace:"
75
+ $output += Get-DotNetStack $process.Id
76
+ $exitCode = 9999
77
+ }
78
+ Stop-Process - InputObject $process
79
+ Remove-Item $outputPath
80
+ if ($exitCode -ne 0 ) {
81
+ if (! $Fatal ) {
82
+ Write-Host " `` $Command `` failed" $output
83
+ } else {
84
+ Die $exitCode " `` $Command `` failed" $output
85
+ }
86
+ }
87
+ $output
88
+ }
89
+
90
+ function Create-TempDirectory {
91
+ $path = Join-Path ([System.IO.Path ]::GetTempPath()) ([System.IO.Path ]::GetRandomFileName())
92
+ New-Item - Type Directory $path
93
+ }
94
+
95
+ Export-ModuleMember - Function Die, Run- Command, Run- Process, Create- TempDirectory
96
+ }
0 commit comments