Public/Invoke-ProcessHelper.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
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
<#
 .Synopsis
  Utility function for executing processes with advance output/error handling options

 .Description
  Utility function for executing processes with advance output/error handling options. This function
  leverages the System.Diagnostics.ProcessStartInfo and System.Diagnostics.Process for invoking an
  executable/batch file.

 .Parameter ProcessFileName
  The path to the executable that will be invoked.

 .Parameter ProcessArguments
  The arguments that will be passed to the process if applicable.

 .Parameter WorkingDirectory
  The directory from which to invoke the process. It may be useful for batch files with relative paths.

 .Parameter LogToFile
  Determines whether or not the standard output/error should be logged to a file. Default is to output to console/in-memory.

 .Parameter TempDirectory
  Path to a temporary directory to dump the standard out/err output. Used when switch LogToFile is specified.

 .Parameter DiscardStandardOut
  If specified, the standard out will not be captured/returned.

 .Parameter DiscardStandardErr
  If specified, the standard err will not be captured/returned.

 .Parameter RunasAdmin
  If specified, the verb runas will be set on the ProcessStartInfo object.
  
 .Example
   # Get the version information of IBM Installation Manager using their command line tool
   Invoke-ProcessHelper "C:\IBM\IIM\eclipse\tools\imcl.exe" @("-version")

 .Example
   # Log the version information of IBM Installation Manager to a temp file
   Invoke-ProcessHelper "C:\IBM\IIM\eclipse\tools\imcl.exe" @("-version") -LogToFile
#>

Function Invoke-ProcessHelper() {
[CmdletBinding(SupportsShouldProcess=$False)]
    Param (
        [Parameter(Mandatory=$True, Position=0)]
        [String]
        [ValidateNotNullOrEmpty()]
        $ProcessFileName,

        [Parameter(Mandatory=$False, Position=1)]
        [String[]]
        $ProcessArguments,

        [Parameter(Mandatory=$False, Position=2)]
        [String]
        $WorkingDirectory,

        [Parameter(Mandatory=$False, Position=3)]
        [String]
        $TempDirectory,
        
        [switch]
        $DiscardStandardOut,

        [switch]
        $DiscardStandardErr,
        
        [switch]
        $LogToFile,
        
        [switch]
        $RunasAdmin
    )
    $currentLocation = Get-Location
    #Validate Parameters
    if (!(Test-Path($ProcessFileName) -PathType Leaf)) {
        Write-Error "Parameter ProcessFileName with value=$ProcessFileName could not be found or is not a valid process path"
    }
    #Compose procStartInfo
    $procStartInfo = New-object System.Diagnostics.ProcessStartInfo
    $procStartInfo.FileName = $ProcessFileName
    $procStartInfo.CreateNoWindow = $true
    $procStartInfo.WindowStyle = "Hidden"
    $procStartInfo.UseShellExecute = $false
    
    if (!($LogToFile.isPresent)) {
        $procStartInfo.RedirectStandardOutput = (!($DiscardStandardOut.IsPresent))
          $procStartInfo.RedirectStandardError = (!($DiscardStandardErr.IsPresent))
    }

    if ($RunasAdmin.isPresent) {
        if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {   
            Write-Verbose("Invoke-ProcessHelper Run as Administrator")
            $procStartInfo.Verb = "runas"
        } else {
            Write-Warning("Current User doesn't have administrator privillages")
        }
    }
    
    #Log handling
    if ($LogToFile.isPresent) {
        $tempDir = (&{if($TempDirectory) {$TempDirectory} else {$env:TEMP}})
        $tmpLog = Join-Path $tempDir "Invoke-Process-$(get-date -f yyyyMMddHHmmss)-$(Get-Random).tmp"
        $stdLog = ($tmpLog + ".std")
        $errLog = ($tmpLog + ".err")
        $ProcessArguments += @("1> $stdLog","2> $errLog")
    }
    
    if (($null -ne $ProcessArguments) -and ($ProcessArguments.Count -gt 0)) {
        $procStartInfo.Arguments = $ProcessArguments
    }

    if ($WorkingDirectory -and (Test-Path $WorkingDirectory)) {
        Set-Location $WorkingDirectory
        $procStartInfo.WorkingDirectory = $WorkingDirectory
    }

    Write-Verbose ("Invoke-ProcessHelper executing: $WorkingDirectory>$ProcessFileName")

    $exitcode = $null 
    $stdout = $null
    $stderr = $null
    
    Try {
        $process = New-Object System.Diagnostics.Process
        Write-Debug ("procStartInfo:"+($procStartInfo | Out-String))
        $process.StartInfo = $procStartInfo
        $process.Start() | Out-Null
            
        if (!($LogToFile.isPresent)) {
            if (!($DiscardStandardOut)) {
                $stdout = $process.StandardOutput.ReadToEnd()
            }
            if (!($DiscardStandardErr)) {
                $stderr = $process.StandardError.ReadToEnd()
            }
        }
        
        $process.WaitForExit()
        $exitcode = $process.ExitCode
    } Catch {
        Write-Error "Invoke-ProcessHelper FAILED $($_.Exception | Out-String)"
    } finally {
        # Set location back
        if ($WorkingDirectory -and (Test-Path $WorkingDirectory)) {
            Set-Location $currentLocation
        }
        if ($LogToFile.isPresent) {
            if (Test-Path($stdLog)) {
                $stdout = Get-Content $stdLog | Out-String
                Remove-Item $stdLog -Force
            }
            
            if (Test-Path($errLog)) {
                $stderr = Get-Content $errLog | Out-String
                Remove-Item $errLog -Force
            }
        }
    }
    
    return [PSCustomObject] @{
        PSTypeName = "BlueShell.Process.Info"
        StdOut = $stdout
        StdErr = $stderr
        ExitCode = $exitcode
    }
}