Invoke-DiskPartScript.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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
Function Invoke-DiskPartScript {
    <#
    .SYNOPSIS
        Run a DiskPart script on one or more remote systems
 
    .FUNCTIONALITY
        Computers
 
    .DESCRIPTION
        Run a DiskPart script on one or more remote systems. Results and errors sent to text files on that system, returned by this function, and filtered as specified.
 
        Command runs via cmd /c on the remote system, not PowerShell.
        Command invoked via Win32_Process Create method.
 
        Returns an object containing the computer, results, errors, command, and pattern.
     
        Be very, very catreful with this. DiskPart can do evil things. Use this at your own risk.
 
    .PARAMETER ComputerName
        Computer(s) to run command on.
 
    .PARAMETER DiskPartText
        Text to run as a DiskPart script
 
    .PARAMETER Pattern
        Optional regular expression to filter results
 
    .PARAMETER ScriptFile
        Temporary file to store DiskPart script on remote system. Must be relative to remote system (not a file share). Default is "C:\DiskPartScript.txt"
 
    .PARAMETER TempOutputFile
        Temporary file to store results on remote system. Must be relative to remote system (not a file share). Default is "C:\DiskPartOutput.txt"
     
    .PARAMETER TempErrorFile
        Temporary file to store redirected errors. Must be relative to remote system (not a file share). Defaults to "C:\DiskPartError.txt"
 
    .PARAMETER Raw
        Return only the output from the command
 
    .EXAMPLE
        Invoke-DiskPartScript -computername wbf, c-is-hyperv-1 -DiskPartText "list volume"
 
        # Run 'list volume' on wbf and c-is-hyperv-1.
 
    .EXAMPLE
        Invoke-DiskPartScript -computername wbf, c-is-hyperv-1 -DiskPartText "list disk" -pattern "offline" | select-object computer, results
 
        # Run 'list disk' on wbf and c-is-hyperv-1. Filter output to lines that match 'offline'. Only display the Computer and Results
 
    .EXAMPLE
        $ScriptContent = Get-Content C:\DiskPart.txt -Raw
        Invoke-DiskPartScript -ComputerName c-is-hyperv-1 -DiskPartText $ScriptContent
 
        # Get the content of an existing diskpart script, use it against C-IS-HYPERV-1.
 
    .LINK
        https://github.com/RamblingCookieMonster/PSDiskPart
 
    .LINK
        Invoke-DiskPartScript
 
    .LINK
        Get-DiskPartDisk
 
    .LINK
        Get-DiskPartVolume
 
    .LINK
        Get-DiskPartVDisk
 
    #>

    [OutputType('System.Management.Automation.PSObject', 'System.String')]
    [CmdletBinding()]
    param(
        [Parameter(
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)]
        [string[]]$ComputerName = $env:COMPUTERNAME,

        $DiskPartText = "list disk",

        $Pattern,

        $ScriptFile = "C:\DiskPartScript.txt",
        
        $TempOutputFile = "C:\DiskPartOutput.txt",

        $TempErrorFile = "C:\DiskPartError.txt",

        [switch]$Raw
    )
    
    Begin
    {

        Function Wait-Path {
            [cmdletbinding()]
            param (
                [string[]]$Path,
                [int]$Timeout = 5,
                [int]$Interval = 1,
                [switch]$Passthru
            )

            $StartDate = Get-Date
            $First = $True

            Do
            {
                #Only sleep if this isn't the first run
                    if($First -eq $True)
                    {
                        $First = $False
                    }
                    else
                    {
                        Start-Sleep -Seconds $Interval
                    }

                #Test paths and collect output
                    [bool[]]$Tests = foreach($PathItem in $Path)
                    {
                        Try
                        {
                            if(Test-Path $PathItem -ErrorAction stop)
                            {
                                Write-Verbose "'$PathItem' exists"
                                $True
                            }
                            else
                            {
                                Write-Verbose "Waiting for '$PathItem'"
                                $False
                            }
                        }
                        Catch
                        {
                            Write-Error "Error testing path '$PathItem': $_"
                            $False
                        }
                    }

                # Identify whether we can see everything
                    $Return = $Tests -notcontains $False -and $Tests -contains $True
        
                # Poor logic, but we break the Until here
                    # Did we time out?
                    # Error if we are not passing through
                    if ( ((Get-Date) - $StartDate).TotalSeconds -gt $Timeout)
                    {
                        if( $Passthru )
                        {
                            $False
                            break
                        }
                        else
                        {
                            Throw "Timed out waiting for paths $($Path -join ", ")"
                        }
                    }
                    elseif($Return)
                    {
                        if( $Passthru )
                        {
                            $True
                        }
                        break
                    }
            }
            Until( $False ) # We break out above
        }

        #Initialize command string and variables for status tracking
            [string]$cmd = "cmd /c diskpart /s $ScriptFile > $TempOutputFile 2> $tempErrorFile"
    }
    
    Process
    {
        foreach($Computer in $ComputerName){
            
            Write-Verbose "Running '$cmd' on '$computer'"

            #define remote file path - computername, drive, folder path
            $remoteTempOutputFile = "\\{0}\{1}`${2}" -f "$computer", (split-path $TempOutputFile -qualifier).TrimEnd(":"), (Split-Path $TempOutputFile -noqualifier)
            $remoteTempErrorFile = "\\{0}\{1}`${2}" -f "$computer", (split-path $tempErrorFile -qualifier).TrimEnd(":"), (Split-Path $tempErrorFile -noqualifier)
            $remoteScriptFile = "\\{0}\{1}`${2}" -f "$computer", (split-path $ScriptFile -qualifier).TrimEnd(":"), (Split-Path $ScriptFile -noqualifier)

            #Attempt to delete any previous results, run command
            Try
            {
                Remove-Item -Path $remoteTempOutputFile, $remoteTempErrorFile -Force -ErrorAction SilentlyContinue -Confirm:$False
                Set-Content -Path $remoteScriptFile -Value $DiskPartText -force -ErrorAction stop
            }
            Catch
            {
                Write-Error "Error preparing $computer`n:$_"
                Continue
            }
            Try
            {
                Wait-Path -Path $remoteScriptFile -Timeout 10 -Interval .5 -ErrorAction stop
                $processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $computer -ErrorAction Stop).processid
            }
            Catch
            {
                Write-Error "Error running '$cmd' on $computer"
                Continue
            }

            #wait for process to complete
            while (
                $(
                    try
                    {
                        Get-Process -Id $processid -ComputerName $computer -ErrorAction Stop
                    }
                    catch
                    {
                        if($_ -like "Cannot find a process with*")
                        {
                            $FALSE
                        }
                        else
                        {
                            Write-Error "Error checking for PID $ProcessId on $Computer`: $_"
                        } 
                    }
                )
            )
            { Start-Sleep -seconds 2 }
        
            #gather results
            if( Wait-Path $remoteTempOutputFile -Timeout 15 -Interval .5 -Passthru )
            {
                if($pattern)
                {
                    $Results = ( Select-String -Path $remoteTempOutputFile -Pattern $Pattern | Select -ExpandProperty Line ) -join "`n"
                }
                else
                {
                    if($PSVersionTable.PSVersion.Major -ge 3)
                    {
                        $results = Get-Content -Path $remoteTempOutputFile -Raw
                    }
                    else
                    {
                        $results = ( Get-Content -Path $remoteTempOutputFile -ReadCount 1500 ) -join "`n"
                    }
                }
            }
            else
            {
                $results = "Results from '$TempOutputFile' on $computer converted to '$remoteTempOutputFile'. This path is not accessible from your system."
            }
            
            #gather errors
            if( Wait-Path -Path $remoteTempErrorFile -Timeout 10 -Interval .5 -Passthru )
            {
                $errors = Get-Content -Path $remoteTempErrorFile
            }
            else
            {
                $results = "Errors from '$tempErrorFile' on $computer converted to '$remoteTempErrorFile'. This path is not accessible from your system."
            }

            if($Raw)
            {
                $Results
                if($Errors)
                {
                    Write-Error $Errors
                }
            }
            else
            {
                #write out the results
                [pscustomobject] @{
                    Computer = $computer
                    Results = $Results
                    Errors = $errors
                    Command = $cmd
                    Pattern = $Pattern
                }
            }

            Remove-Item -Path $remoteTempOutputFile, $remoteScriptFile, $remoteTempErrorFile -Force -ErrorAction SilentlyContinue
        }
    }

}