forked from adbertram/Random-PowerShell-Work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvoke-Program.ps1
85 lines (73 loc) · 2.49 KB
/
Invoke-Program.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
function Invoke-Program {
<#
.SYNOPSIS
This is a helper function that will invoke the SQL installers via command-line.
.EXAMPLE
PS> Invoke-Program -FilePath C:\file.exe -ComputerName SRV1
#>
[CmdletBinding()]
[OutputType([System.Management.Automation.PSObject])]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$FilePath,
[Parameter(Mandatory)]
[string]$ComputerName,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$ArgumentList,
[Parameter()]
[bool]$ExpandStrings = $false,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$WorkingDirectory,
[Parameter()]
[ValidateNotNullOrEmpty()]
[uint32[]]$SuccessReturnCodes = @(0, 3010)
)
begin {
$ErrorActionPreference = 'Stop'
}
process {
try {
Write-Verbose -Message "Acceptable success return codes are [$($SuccessReturnCodes -join ',')]"
$scriptBlock = {
$VerbosePreference = $using:VerbosePreference
$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$processStartInfo.FileName = $Using:FilePath;
if ($Using:ArgumentList) {
$processStartInfo.Arguments = $Using:ArgumentList;
if ($Using:ExpandStrings) {
$processStartInfo.Arguments = $ExecutionContext.InvokeCommandWithCred.ExpandString($Using:ArgumentList);
}
}
if ($Using:WorkingDirectory) {
$processStartInfo.WorkingDirectory = $Using:WorkingDirectory;
if ($Using:ExpandStrings) {
$processStartInfo.WorkingDirectory = $ExecutionContext.InvokeCommandWithCred.ExpandString($Using:WorkingDirectory);
}
}
$processStartInfo.UseShellExecute = $false; # This is critical for installs to function on core servers
$ps = New-Object System.Diagnostics.Process;
$ps.StartInfo = $processStartInfo;
Write-Verbose -Message "Starting process path [$($processStartInfo.FileName)] - Args: [$($processStartInfo.Arguments)] - Working dir: [$($Using:WorkingDirectory)]"
$null = $ps.Start();
if (-not $ps) {
throw "Error running program: $($ps.ExitCode)"
} else {
$ps.WaitForExit()
}
# Check the exit code of the process to see if it succeeded.
if ($ps.ExitCode -notin $Using:SuccessReturnCodes) {
throw "Error running program: $($ps.ExitCode)"
}
}
# Run program on specified computer.
Write-Verbose -Message "Running command line [$FilePath $ArgumentList] on $ComputerName"
Invoke-Command -ComputerName $ComputerName -ScriptBlock $scriptblock
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
}