forked from freedbygrace/Invoke-OperatingSystemDiskDetection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-OperatingSystemDiskDetection.ps1
More file actions
394 lines (324 loc) · 24.1 KB
/
Copy pathInvoke-OperatingSystemDiskDetection.ps1
File metadata and controls
394 lines (324 loc) · 24.1 KB
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
<#
.SYNOPSIS
Dynamically determines the desired operating system disk based on a calculated MediaType and BusType priority.
.DESCRIPTION
This solves for issues in devices that have multiple hard disk(s) where operating system gets installed onto the incorrect disk.
This method bypasses any manual determination required across all models and devices.
.PARAMETER BusTypeExclusionExpression
A valid regular expression to exclude disks for from consideration based on their bus type. By default, USB based disks will be excluded.
.PARAMETER DiskSizeThresholdInGB
Grants the ability to filter out disks that are smaller than the specified value in gigabytes. This is useful for situations where an Intel Optane Memory Cache might be present.
.NOTES
By default, the operating system will get deployed onto the fatest and smallest disk.
If a task sequence is running, the required task sequence variables (More can be added) will be configured so that the Format and Partition steps will format the correct hard disk.
.LINK
https://learn.microsoft.com/en-us/windows-hardware/drivers/storage/msft-Disk
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param
(
[Parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]
[Alias('BTEE')]
[Regex]$BusTypeExclusionExpression = '(^USB$)',
[Parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]
[Alias('DST')]
[UInt64]$DiskSizeThresholdInGB = 32
)
Try
{
#Define variables
$LoggingDetails = New-Object -TypeName 'System.Collections.Specialized.OrderedDictionary'
$LoggingDetails.Add('LogMessage', $Null)
$LoggingDetails.Add('WarningMessage', $Null)
$LoggingDetails.Add('ErrorMessage', $Null)
$DateTimeMessageFormat = 'MM/dd/yyyy HH:mm:ss.FFF' ###03/23/2022 11:12:48.347###
[ScriptBlock]$GetCurrentDateTimeMessageFormat = {(Get-Date).ToString($DateTimeMessageFormat)}
$OutputObjectProperties = New-Object -TypeName 'System.Collections.Specialized.OrderedDictionary'
#Define the error handling definition
[ScriptBlock]$ErrorHandlingDefinition = {
Param
(
[Int16]$Severity,
[Boolean]$Terminate
)
If (($Null -ieq $Script:LASTEXITCODE) -or ($Script:LASTEXITCODE -eq 0))
{
[Int]$Script:LASTEXITCODE = 6000
}
$ExceptionPropertyDictionary = New-Object -TypeName 'System.Collections.Specialized.OrderedDictionary'
$ExceptionPropertyDictionary.Add('Message', $_.Exception.Message)
$ExceptionPropertyDictionary.Add('Category', $_.Exception.ErrorRecord.FullyQualifiedErrorID)
$ExceptionPropertyDictionary.Add('LineNumber', $_.InvocationInfo.ScriptLineNumber)
$ExceptionPropertyDictionary.Add('LinePosition', $_.InvocationInfo.OffsetInLine)
$ExceptionPropertyDictionary.Add('Code', $_.InvocationInfo.Line.Trim())
$ExceptionMessageList = New-Object -TypeName 'System.Collections.Generic.List[String]'
ForEach ($ExceptionProperty In $ExceptionPropertyDictionary.GetEnumerator())
{
$ExceptionMessageList.Add("[$($ExceptionProperty.Key): $($ExceptionProperty.Value)]")
}
$LogMessageParameters = New-Object -TypeName 'System.Collections.Specialized.OrderedDictionary'
$LogMessageParameters.Message = $ExceptionMessageList -Join ' '
$LogMessageParameters.Verbose = $True
Switch ($Severity)
{
{($_ -in @(1))} {Write-Verbose @LogMessageParameters}
{($_ -in @(2))} {Write-Warning @LogMessageParameters}
{($_ -in @(3))} {Write-Error @LogMessageParameters}
}
Switch ($Terminate)
{
{($_ -eq $True)}
{
Throw
}
}
}
#Import the required modules
$RequiredModuleList = New-Object -TypeName 'System.Collections.Generic.List[String]'
$RequiredModuleList.Add('Storage')
ForEach ($RequiredModule In $RequiredModuleList)
{
Try
{
$RequiredModuleInfo = Try {Get-Module -Name ($RequiredModule)} Catch {$Null}
Switch ($Null -ieq $RequiredModuleInfo)
{
{($_ -eq $True)}
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Attempting to load required Module `"$($RequiredModule)`". Please Wait..."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
$Null = Import-Module -Name ($RequiredModule) -Force -DisableNameChecking
}
}
}
Catch
{
$ErrorHandlingDefinition.Invoke(2, $True)
}
Finally
{
}
}
#Determine if a task sequence is running or not
Try
{
[System.__ComObject]$TSEnvironment = New-Object -ComObject "Microsoft.SMS.TSEnvironment"
If ($Null -ine $TSEnvironment)
{
$IsRunningTaskSequence = $True
[Boolean]$IsConfigurationManagerTaskSequence = [String]::IsNullOrEmpty($TSEnvironment.Value("_SMSTSPackageID")) -eq $False
Switch ($IsConfigurationManagerTaskSequence)
{
{($_ -eq $True)}
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - A Microsoft Endpoint Configuration Manager (MECM) task sequence was detected."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
}
{($_ -eq $False)}
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - A Microsoft Deployment Toolkit (MDT) task sequence was detected."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
}
}
}
}
Catch
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - A task sequence was not detected."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
$IsRunningTaskSequence = $False
}
#Define any scriptblocks for determining calculated properties
[ScriptBlock]$DetermineMediaTypePriority = {
Switch -Regex ($_.MediaType)
{
'(^4$)|(^SSD$)' {1}
'(^3$)|(^HDD$)' {2}
'(^5$)|(^SCM$)' {3}
'(^0$)|(^Unspecified$)' {4}
}
}
[ScriptBlock]$DetermineBusTypePriority = {
Switch -Regex ($_.BusType)
{
'(^17$)|(^NVMe$)' {1}
'(^11$)|(^SATA$)' {2}
'(^8$)|(^RAID$)' {3}
'(^10$)|(^SAS$)' {4}
'(^12$)|(^SD$)' {5}
'(^7$)|(^USB$)' {6}
'(^1$)|(^SCSI$)' {7}
'(^6$)|(^Fibre Channel$)' {8}
'(^3$)|(^ATA$)' {9}
'(^15$)|(^File Backed Virtual$)' {10}
'(^2$)|(^ATAPI$)' {11}
'(^4$)|(^1394$)' {12}
'(^5$)|(^SSA$)' {13}
'(^9$)|(^iSCSI$)' {14}
'(^13$)|(^MMC$)' {15}
'(^14$)|(^MAX$)' {16}
'(^16$)|(^Storage Spaces$)' {17}
'(^0$)|(^Unknown$)' {18}
'(^18$)|(^Microsoft Reserved$)' {19}
}
}
#Get the physical disks attached to the device
$DiskPropertyList = New-Object -TypeName 'System.Collections.Generic.List[System.Object]'
$DiskPropertyList.Add(@{Name = 'DiskNumber'; Expression = {$_.DeviceID}})
$DiskPropertyList.Add('Manufacturer')
$DiskPropertyList.Add('FriendlyName')
$DiskPropertyList.Add('Model')
$DiskPropertyList.Add('SerialNumber')
$DiskPropertyList.Add('MediaType')
$DiskPropertyList.Add(@{Name = 'MediaTypePriority'; Expression = ($DetermineMediaTypePriority)})
$DiskPropertyList.Add('BusType')
$DiskPropertyList.Add(@{Name = 'BusTypePriority'; Expression = ($DetermineBusTypePriority)})
$DiskPropertyList.Add(@{Name = 'SizeInGB'; Expression = {[System.Math]::Round(($_.Size / 1GB), 2)}})
$DiskPropertyList.Add(@{Name = 'SizeInBytes'; Expression = {$_.Size}})
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Attempting to search for any disk(s) matching the specified criteria. Please Wait..."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
[UInt64]$DiskSizeThresholdInBytes = $DiskSizeThresholdInGB * 1GB
[ScriptBlock]$DiskListerCriteria = {($_.BusType -inotmatch $BusTypeExclusionExpression) -and ($_.Size -gt $DiskSizeThresholdInBytes)}
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Disk List Criteria: $($DiskListerCriteria)"
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
$OutputObjectProperties.DiskList = Get-PhysicalDisk | Where-Object -FilterScript ($DiskListerCriteria) | Sort-Object -Property @('MediaTypePriority', 'BusTypePriority', 'Size') | Select-Object -Property ($DiskPropertyList)
$OutputObjectProperties.DiskListCount = ($OutputObjectProperties.DiskList | Measure-Object).Count
$OutputObjectProperties.DesiredOperatingSystemDisk = $Null
$OutputObjectProperties.DesiredOperatingSystemDiskLocated = $False
$OutputObjectProperties.IsTaskSequenceRunning = $IsRunningTaskSequence
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Detected $($OutputObjectProperties.DiskListCount) disk(s) meeting the specified criteria."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
Switch ($OutputObjectProperties.DiskListCount -gt 0)
{
{($_ -eq $True)}
{
ForEach ($Disk In $OutputObjectProperties.DiskList)
{
$DiskLogMessageList = New-Object -TypeName 'System.Collections.Generic.List[System.String]'
ForEach ($DiskProperty In $Disk.PSObject.Properties)
{
$DiskPropertyLogMessage = "[$($DiskProperty.Name): $($DiskProperty.Value)]"
$DiskLogMessageList.Add($DiskPropertyLogMessage)
}
$DiskLogMessage = $DiskLogMessageList -Join ' '
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - $($DiskLogMessage)"
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
}
$DiskListByMediaTypePriority = $OutputObjectProperties.DiskList | Group-Object -Property 'MediaTypePriority' | Sort-Object -Property {[UInt32]::Parse($_.Name)}
:MediaTypePriorityLoop ForEach ($MediaTypePriority In $DiskListByMediaTypePriority)
{
Switch ($MediaTypePriority.Count -gt 0)
{
{($_ -eq $True)}
{
$MediaTypePriorityGroup = $MediaTypePriority.Group
$MediaTypePriorityGroupName = $MediaTypePriorityGroup[0].MediaType
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Attempting to process media type group `"$($MediaTypePriorityGroupName)`" [Priority: $($MediaTypePriority.Name)]. Please Wait..."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
$DiskListByBusTypePriority = $MediaTypePriorityGroup | Group-Object -Property 'BusTypePriority' | Sort-Object -Property {[UInt32]::Parse($_.Name)}
:BusTypePriorityLoop ForEach ($BusTypePriority In $DiskListByBusTypePriority)
{
$BusTypePriorityGroup = $BusTypePriority.Group
$BusTypePriorityGroupName = $BusTypePriorityGroup[0].BusType
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Attempting to process bus type group `"$($BusTypePriorityGroupName)`" [Priority: $($BusTypePriority.Name)]. Please Wait..."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
Switch ($BusTypePriority.Count -gt 0)
{
{($_ -eq $True)}
{
$OutputObjectProperties.DesiredOperatingSystemDisk = $BusTypePriorityGroup | Select-Object -First 1
Switch ($Null -ine $OutputObjectProperties.DesiredOperatingSystemDisk)
{
{($_ -eq $True)}
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - The desired operating system disk was found in media type group `"$($MediaTypePriorityGroupName)`" [Priority: $($MediaTypePriority.Name)] and bus type group `"$($BusTypePriorityGroupName)`" [Priority: $($BusTypePriority.Name)]."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
$OutputObjectProperties.DesiredOperatingSystemDiskLocated = $True
Break MediaTypePriorityLoop
}
}
}
}
}
}
}
}
Switch ($OutputObjectProperties.DesiredOperatingSystemDiskLocated)
{
{($_ -eq $True)}
{
ForEach ($DesiredOperatingSystemDiskProperty In $OutputObjectProperties.DesiredOperatingSystemDisk.PSObject.Properties)
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - $($DesiredOperatingSystemDiskProperty.Name): $($DesiredOperatingSystemDiskProperty.Value -Join ', ')"
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
}
$GetDiskInfo = {Get-Disk -Number ($OutputObjectProperties.DesiredOperatingSystemDisk.DiskNumber)}
$DiskInfo = $GetDiskInfo.InvokeReturnAsIs()
Switch ($DiskInfo.IsOffline)
{
{($_ -eq $True)}
{
$LoggingDetails.WarningMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Disk $($DiskInfo.Number) is currently in `"Offline`" mode and will be set to `"Online`" mode. Please Wait..."
Write-Verbose -Message ($LoggingDetails.WarningMessage) -Verbose
$Null = Set-Disk -Number ($DiskInfo.Number) -IsOffline:$False
$DiskInfo = $GetDiskInfo.InvokeReturnAsIs()
}
{($_ -eq $False)}
{
$LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Disk $($DiskInfo.Number) is already set to `"Online`" mode. Skipping operation..."
Write-Verbose -Message "$($LogMessage)" -Verbose
}
}
Switch ($DiskInfo.IsReadOnly)
{
{($_ -eq $True)}
{
$LoggingDetails.WarningMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Disk $($DiskInfo.Number) is currently in `"Read-Only`" mode and will be set to `"Read-Write`" mode. Please Wait..."
Write-Verbose -Message ($LoggingDetails.WarningMessage) -Verbose
$Null = Set-Disk -Number ($DiskInfo.Number) -IsReadOnly:$False
$DiskInfo = $GetDiskInfo.InvokeReturnAsIs()
}
{($_ -eq $False)}
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Disk $($DiskInfo.Number) is already set to `"Read-Write`" mode. Skipping operation..."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
}
}
Switch ($IsRunningTaskSequence)
{
{($_ -eq $True)}
{
$TSVariableDictionary = New-Object -TypeName 'System.Collections.Specialized.OrderedDictionary'
$TSVariableDictionary.'OSDDiskIndex' = $OutputObjectProperties.DesiredOperatingSystemDisk.DiskNumber
$TSVariableDictionary.'OSDiskNumber' = $OutputObjectProperties.DesiredOperatingSystemDisk.DiskNumber
$TSVariableDictionary.'OSDDiskCount' = $OutputObjectProperties.DiskListCount
Switch ($TSVariableDictionary.Keys.Count -gt 0)
{
{($_ -eq $True)}
{
ForEach ($TSVariable In $TSVariableDictionary.GetEnumerator())
{
$LoggingDetails.LogMessage = "$($GetCurrentDateTimeMessageFormat.Invoke()) - Attempting to the value of task sequence variable `"$($TSVariable.Key)`" to `"$($TSVariable.Value)`". Please Wait..."
Write-Verbose -Message ($LoggingDetails.LogMessage) -Verbose
$TSEnvironment.Value($TSVariable.Key) = $TSVariable.Value
}
}
}
}
}
}
}
}
}
}
Catch
{
$ErrorHandlingDefinition.Invoke(2, $True)
}
Finally
{
$OutputObject = New-Object -TypeName 'System.Management.Automation.PSObject' -Property ($OutputObjectProperties)
Write-Output -InputObject ($OutputObject)
}