-
Notifications
You must be signed in to change notification settings - Fork 1
/
Get-HyperVVMGenerationNumberFromWithinVM.ps1
618 lines (580 loc) · 27.5 KB
/
Get-HyperVVMGenerationNumberFromWithinVM.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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#region License
###############################################################################################
# Copyright 2020 Frank Lesniak
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###############################################################################################
#endregion License
function Split-StringOnLiteralString {
# This function takes two positional arguments
# The first argument is a string, and the string to be split
# The second argument is a string or char, and it is that which is to split the string in the first parameter
#
# Note: This function always returns an array, even when there is zero or one element in it.
#
# Example:
# $result = Split-StringOnLiteralString "foo" " "
# # $result.GetType().FullName is System.Object[]
# # $result.Count is 1
#
# Example 2:
# $result = Split-StringOnLiteralString "What do you think of this function?" " "
# # $result.Count is 7
trap {
Write-Error "An error occurred using the Split-StringOnLiteralString function. This was most likely caused by the arguments supplied not being strings"
}
if ($args.Length -ne 2) {
Write-Error "Split-StringOnLiteralString was called without supplying two arguments. The first argument should be the string to be split, and the second should be the string or character on which to split the string."
} else {
if ($null -eq $args[0]) {
# String to be split was $null; return an empty array. Leading comma ensures that
# PowerShell cooperates and returns the array as desired (without collapsing it)
, @()
} elseif ($null -eq $args[1]) {
# Splitter was $null; return string to be split within an array (of one element).
# Leading comma ensures that PowerShell cooperates and returns the array as desired
# (without collapsing it
, ($args[0])
} else {
if (($args[0]).GetType().Name -ne "String") {
Write-Warning "The first argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strToSplit = [string]$args[0]
} else {
$strToSplit = $args[0]
}
if ((($args[1]).GetType().Name -ne "String") -and (($args[1]).GetType().Name -ne "Char")) {
Write-Warning "The second argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strSplitter = [string]$args[1]
} elseif (($args[1]).GetType().Name -eq "Char") {
$strSplitter = [string]$args[1]
} else {
$strSplitter = $args[1]
}
$strSplitterInRegEx = [regex]::Escape($strSplitter)
# With the leading comma, force encapsulation into an array so that an array is
# returned even when there is one element:
, [regex]::Split($strToSplit, $strSplitterInRegEx)
}
}
}
function Get-PathToDotNetRuntimeEnvironment {
$strPathToDotNetRuntimeEnvironment = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
# We have the path, but it has a trailing backslash. Let's remove it
$guid = [guid]::NewGuid()
$strGUID = $guid.Guid
$strWorkingPath = Join-Path $strPathToDotNetRuntimeEnvironment $strGUID
$arrPath = Split-StringOnLiteralString $strWorkingPath $strGUID
$strPathWithSeparatorButWithoutGUID = $arrPath[0]
$strScrubbedPath = $strPathWithSeparatorButWithoutGUID.Substring(0, $strPathWithSeparatorButWithoutGUID.Length - 1)
$strScrubbedPath
}
function Build-CSharpInMemory {
Param (
[string]$strCSharpCodeToCompile,
[array]$arrAdditionalReferences
)
$CSharpCodeProvider = New-Object Microsoft.CSharp.CSharpCodeProvider
$ArrayListReferences = New-Object Collections.ArrayList
$ArrayListReferences.AddRange( `
@( `
(Join-Path (Get-PathToDotNetRuntimeEnvironment) "System.dll"),
[PSObject].Assembly.Location
)
)
if ($arrAdditionalReferences -ne $null) {
if ($arrAdditionalReferences.Count -ge 1) {
$ArrayListReferences.AddRange($arrAdditionalReferences)
}
}
$CompilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$CompilerParameters.GenerateInMemory = $true
$CompilerParameters.GenerateExecutable = $false
$CompilerParameters.OutputAssembly = "custom"
$CompilerParameters.ReferencedAssemblies.AddRange($ArrayListReferences)
$CompilerResults = $CSharpCodeProvider.CompileAssemblyFromSource($CompilerParameters, $strCSharpCodeToCompile)
if ($CompilerResults.Errors.Count) {
$arrCSharpCodeLines = $strCSharpCodeToCompile.Split("`n")
foreach ($CompilerError in $CompilerResults.Errors) {
Write-Host "Error: $($arrCSharpCodeLines[$($CompilerError.Line - 1)])"
$CompilerError | Out-Default
}
Throw "INVALID DATA: Errors encountered while compiling code"
}
}
function Get-PSVersion {
if (Test-Path variable:\PSVersionTable) {
$PSVersionTable.PSVersion
} else {
[version]("1.0")
}
}
function Test-Windows {
$versionPS = Get-PSVersion
if ($versionPS.Major -ge 6) {
$IsWindows
} else {
$true
}
}
function Get-WindowsOSVersion {
$boolWindows = Test-Windows
if ($boolWindows) {
$versionPS = Get-PSVersion
if ($versionPS.Major -ge 3) {
$arrCIMInstanceOS = @(Get-CimInstance -Query "Select Version from Win32_OperatingSystem")
if ($arrCIMInstanceOS.Count -eq 0) {
Write-Error "No instances of Win32_OperatingSystem found!"
$null
}
if ($arrCIMInstanceOS.Count -gt 1) {
Write-Warning "More than one instance of Win32_OperatingSystem returned. Will only use first instance."
}
if ($arrCIMInstanceOS.Count -ge 1) {
[System.Version](($arrCIMInstanceOS[0]).Version)
}
} else {
$arrManagementObjectOS = @(Get-WmiObject -Query "Select Version from Win32_OperatingSystem")
if ($arrManagementObjectOS.Count -eq 0) {
Write-Error "No instances of Win32_OperatingSystem found!"
$null
}
if ($arrManagementObjectOS.Count -gt 1) {
Write-Warning "More than one instance of Win32_OperatingSystem returned. Will only use first instance."
}
if ($arrManagementObjectOS.Count -ge 1) {
[System.Version](($arrManagementObjectOS[0]).Version)
}
}
} else {
$null
}
}
function Get-PathToWindowsFolder {
$boolWindows = Test-Windows
if ($boolWindows) {
$env:windir
} else {
$null
}
}
function Get-PathToWindowsSetupLog {
$strWindowsPath = Get-PathToWindowsFolder
if ($null -ne $strWindowsPath) {
$strWorkingPath = Join-Path $strWindowsPath "Panther"
$strWorkingPath = Join-Path $strWorkingPath "setupact.log"
$strWorkingPath
} else {
$null
}
}
function Get-DetectedBootEnvironmentFromWindowsSetupLog {
# Returns a string containing the "detected boot environment" from the Windows Setup log.
# If the log could not be read, or if this function is run on non-Windows, the function
# returns $null
#
#region OriginalLicense
# Although substantial modifications have been made, the original portions of
# Get-LogFileFirmwareType that are incorporated into
# Get-DetectedBootEnvironmentFromWindowsSetupLog are subject to the following license:
###########################################################################################
# Copyright (c) 2015 Chris Warwick
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###########################################################################################
#endregion OriginalLicense
$versionPS = Get-PSVersion
$strPathToWindowsSetupLog = Get-PathToWindowsSetupLog
if ($null -ne $strPathToWindowsSetupLog) {
if ($versionPS.Major -ge 3) {
$arrMatchInfo = @(Select-String 'Detected boot environment' $strPathToWindowsSetupLog -AllMatches -ErrorAction Ignore)
} else {
$arrMatchInfo = @(Select-String 'Detected boot environment' $strPathToWindowsSetupLog -AllMatches -ErrorAction SilentlyContinue)
}
if ($arrMatchInfo.Count -ge 1) {
$arrStrBootEnvironments = @($arrMatchInfo | ForEach-Object {
($_.Line) -replace ".*:\s+"
})
if ($arrStrBootEnvironments.Count -gt 1) {
Write-Warning ("More than one detected boot environment found in Windows Setup Log (" + $strPathToWindowsSetupLog + "). Returning only first one.")
}
$arrStrBootEnvironments[0]
} else {
Write-Warning ("Read access to file " + $strPathToWindowsSetupLog + " was denied; try running PowerShell as an administrator (elevated)")
$null
}
} else {
$null
}
}
function Test-FirmwareEnvironmentVariableAWin32API {
# Returns $true if the GetFirmwareEnvironmentVariableA Win32 API is able to be called,
# which indicates that the system is UEFI. Returns $false otherwise.
#
# NOTE: Returns $null if run on non-Windows system
#
#region OriginalLicense
# Although substantial modifications have been made, the original portions of
# Get-FirmwareEnvironmentVariableAPI that are incorporated into
# Test-FirmwareEnvironmentVariableAWin32API are subject to the following license:
###########################################################################################
# Copyright (c) 2015 Chris Warwick
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###########################################################################################
#endregion OriginalLicense
# Use the GetFirmwareEnvironmentVariable Win32 API.
# From MSDN
# (http://msdn.microsoft.com/en-ca/library/windows/desktop/ms724325%28v=vs.85%29.aspx):
# "Firmware variables are not supported on a legacy BIOS-based system. The
# GetFirmwareEnvironmentVariable function will always fail on a legacy BIOS-based system,
# or if Windows was installed using legacy BIOS on a system that supports both legacy BIOS
# and UEFI."
# "To identify these conditions, call the function with a dummy firmware environment name
# such as an empty string ("") for the lpName parameter and a dummy GUID such as
# "{00000000-0000-0000-0000-000000000000}" for the lpGuid parameter. On a legacy BIOS-based
# system, or on a system that supports both legacy BIOS and UEFI where Windows was
# installed using legacy BIOS, the function will fail with ERROR_INVALID_FUNCTION. On a
# UEFI-based system, the function will fail with an error specific to the firmware, such as
# ERROR_NOACCESS, to indicate that the dummy GUID namespace does not exist."
#
# From PowerShell, we can call the API via P/Invoke from a compiled C# class using
# Add-Type. In Win32 any resulting API error is retrieved using GetLastError(), however,
# this is not reliable in .Net (see
# blogs.msdn.com/b/adam_nathan/archive/2003/04/25/56643.aspx), instead we mark the pInvoke
# signature for GetFirmwareEnvironmentVariableA with SetLastError=true and use
# Marshal.GetLastWin32Error()
#
# Note: The GetFirmwareEnvironmentVariable API requires the SE_SYSTEM_ENVIRONMENT_NAME
# privilege. In the Security Policy editor this equates to "User Rights Assignment":
# "Modify firmware environment values" and is granted to Administrators by default. Because
# we don't actually read any variables this permission appears to be optional.
$boolWindows = Test-Windows
if ($boolWindows) {
$versionWindows = Get-WindowsOSVersion
if ($versionWindows -ge ([System.Version]"6.1")) {
$strCSharpCode = @"
using System;
using System.Runtime.InteropServices;
namespace FrankLesniak
{
public class CheckUEFI
{
[DllImport("kernel32.dll", SetLastError=true)]
static extern UInt32
GetFirmwareEnvironmentVariableA(string lpName, string lpGuid, IntPtr pBuffer, UInt32 nSize);
const int ERROR_INVALID_FUNCTION = 1;
public static bool IsUEFI()
{
// Try to call the GetFirmwareEnvironmentVariable API. This is invalid on legacy BIOS.
GetFirmwareEnvironmentVariableA("","{00000000-0000-0000-0000-000000000000}",IntPtr.Zero,0);
if (Marshal.GetLastWin32Error() == ERROR_INVALID_FUNCTION)
return false; // API not supported (INVALID_FUNCTION); this is a legacy BIOS
else
return true; // Call to API is supported. This is UEFI.
}
}
}
"@
$versionPS = Get-PSVersion
if ($versionPS.Major -ge 2) {
Add-Type -Language CSharp -TypeDefinition $strCSharpCode
} else {
Build-CSharpInMemory $strCSharpCode
}
[FrankLesniak.CheckUEFI]::IsUEFI()
} else {
# Is Windows, but is a version that does not support
# GetFirmwareEnvironmentVariableA API
$null
}
} else {
# Not Windows
$null
}
}
function Get-FirmwareTypeFromGetFirmwareTypeWin32API {
# Returns an integer that indicates the firmware type on the system.
# Returns:
# 0 if the type is unknown
# 1 if the type is BIOS
# 2 if the type is UEFI
# 3 if the type is "Max"
#
# NOTE: Returns $null if run on non-Windows system
#
#region OriginalLicense
# Although substantial modifications have been made, the original portions of
# Get-FirmwareTypeAPI that are incorporated into
# Get-FirmwareTypeFromGetFirmwareTypeWin32API are subject to the following license:
###########################################################################################
# Copyright (c) 2015 Chris Warwick
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###########################################################################################
#endregion OriginalLicense
#
# In Windows 8/Server 2012 and above there's an API that directly returns the firmware type
# and doesn't rely on a hack. GetFirmwareType() in kernel32.dll
# (http://msdn.microsoft.com/en-us/windows/desktop/hh848321%28v=vs.85%29.aspx) returns a
# pointer to a FirmwareType enum that defines the following:
#
# typedef enum _FIRMWARE_TYPE {
# FirmwareTypeUnknown = 0,
# FirmwareTypeBios = 1,
# FirmwareTypeUefi = 2,
# FirmwareTypeMax = 3
# } FIRMWARE_TYPE, *PFIRMWARE_TYPE;
# This API call can be called in .Net via P/Invoke.
$boolWindows = Test-Windows
if ($boolWindows) {
$versionWindows = Get-WindowsOSVersion
if ($versionWindows -ge ([System.Version]"6.2")) {
$strCSharpCode = @"
using System;
using System.Runtime.InteropServices;
namespace FrankLesniak
{
public class FirmwareType
{
[DllImport("kernel32.dll")]
static extern bool GetFirmwareType(ref uint FirmwareType);
public static uint GetFirmwareType()
{
uint firmwaretype = 0;
if (GetFirmwareType(ref firmwaretype))
return firmwaretype;
else
return 0; // API call failed, just return 'unknown'
}
}
}
"@
$versionPS = Get-PSVersion
if ($versionPS.Major -ge 2) {
Add-Type -Language CSharp -TypeDefinition $strCSharpCode
} else {
Build-CSharpInMemory $strCSharpCode
}
[FrankLesniak.FirmwareType]::GetFirmwareType()
} else {
# Is Windows, but is a version that does not support
# GetFirmwareEnvironmentVariableA API
$null
}
} else {
# Not Windows
$null
}
}
function Test-UEFISystem {
# Returns $true if the system is UEFI
# Returns $false if the system is not UEFI (i.e., it is BIOS)
# Returns $null if the system type could not be determined
#
#region OriginalLicense
# Although substantial modifications have been made, the original portions of
# Get-FirmwareType that are incorporated into Test-UEFISystem are subject to the following
# license:
###########################################################################################
# Copyright (c) 2015 Chris Warwick
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###########################################################################################
#endregion OriginalLicense
$boolWindows = Test-Windows
if ($boolWindows) {
$versionWindowsOS = Get-WindowsOSVersion
if ($versionWindowsOS -lt ([System.Version]"6.0")) {
# Windows 5.x running PowerShell - these do not support UEFI
$false
} elseif ($versionWindowsOS -ge ([System.Version]"6.2")) {
# Windows 8 / Windows Server 2012, or newer
$intFirmwareType = Get-FirmwareTypeFromGetFirmwareTypeWin32API
if ($null -ne $intFirmwareType) {
if ($intFirmwareType -eq 2) {
$true # UEFI
} else {
$false # Not UEFI, must be BIOS
}
} else {
# Error condition
$null
}
} elseif ($versionWindowsOS -ge ([System.Version]"6.1")) {
# Windows 7 / Windows Server 2008 R2
Test-FirmwareEnvironmentVariableAWin32API
} else {
$strDetectedBootEnvironment = Get-DetectedBootEnvironmentFromWindowsSetupLog
switch -Regex ($strDetectedBootEnvironment) {
"^U?EFI$" {
$true
}
default {
$false
}
}
}
} else {
# TO-DO: write code for FreeBSD/Linux
# return $null for now
$null
}
}
function Get-HardwareModel {
$boolWindows = Test-Windows
if ($boolWindows) {
$versionPS = Get-PSVersion
if ($versionPS.Major -ge 3) {
$arrCIMInstanceComputerSystem = @(Get-CimInstance -Query "Select Model from Win32_ComputerSystem")
if ($arrCIMInstanceComputerSystem.Count -eq 0) {
Write-Error "No instances of Win32_ComputerSystem found!"
$null
}
if ($arrCIMInstanceComputerSystem.Count -gt 1) {
Write-Warning "More than one instance of Win32_ComputerSystem returned. Will only use first instance."
}
if ($arrCIMInstanceComputerSystem.Count -ge 1) {
($arrCIMInstanceComputerSystem[0]).Model
}
} else {
$arrManagementObjectComputerSystem = @(Get-WmiObject -Query "Select Model from Win32_ComputerSystem")
if ($arrManagementObjectComputerSystem.Count -eq 0) {
Write-Error "No instances of Win32_ComputerSystem found!"
$null
}
if ($arrManagementObjectComputerSystem.Count -gt 1) {
Write-Warning "More than one instance of Win32_ComputerSystem returned. Will only use first instance."
}
if ($arrManagementObjectComputerSystem.Count -ge 1) {
($arrManagementObjectComputerSystem[0]).Model
}
}
} else {
# TO-DO: Find a way to do this on FreeBSD/Linux
# Return $null for now
$null
}
}
function Test-ThisSystemIsAHyperVVM {
$boolWindows = Test-Windows
if ($boolWindows) {
$strModel = Get-HardwareModel
if ($null -ne $strModel) {
if ($strModel -eq "Virtual Machine") {
$true
} else {
$false
}
} else {
$null # Error condition
}
} else {
# TO-DO: Find a way to do this on FreeBSD/Linux
# Return $null for now
$null
}
}
function Get-HyperVVMGenerationNumberFromWithinVM {
# Returns an integer indicating the Hyper-V VM generation number of this system
# Returns 2 if this system is a Hyper-V VM running as a "Generation 2" Hyper-V VM
# Returns 1 if this system is a Hyper-V VM running as a "Generation 1" Hyper-V VM
# Note: Microsoft Virtual Server and Virtual PC VMs can also return 1
# Returns 0 if this system is a Hyper-V VM, but the generation number could not be
# determined due to an error. Usually this would only occur if the VM is Vista/Windows
# Server 2008 system and the PowerShell script was run without administrative privileges.
# Check the Warning stream for more information.
# Note: Microsoft Virtual Server and Virtual PC VMs can also return 0
# Returns -1 if this system is not a Hyper-V VM
$boolHyperVVM = Test-ThisSystemIsAHyperVVM
if ($null -ne $boolHyperVVM) {
if ($boolHyperVVM) {
$boolUEFI = Test-UEFISystem
if ($null -ne $boolUEFI) {
if ($boolUEFI) {
# Hyper-V VM with UEFI
# Generation 2
2
} else {
# Hyper-V VM not running UEFI
# Generation 1
1
}
} else {
# Is a Hyper-V VM but could not determine whether UEFI is running
# Error condition
0
}
} else {
# Not a Hyper-V VM
-1
}
} else {
$null
}
}