Dictionaries/Computer.Dict.Windows/Computer.Dict.Windows.psm1
|
<#
###### ####### ## ## ######## ## ## ######## ######## ######## ## ## ## ## ### ### ## ## ## ## ## ## ## ## ## ## ## #### #### ## ## ## ## ## ## ## ## ## ## ## ## ### ## ######## ## ## ## ###### ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ####### ## ## ## ####### ## ######## ## ## #> # function Get-MyInvocation { # [CmdletBinding()] # [OutputType([String])] # Param ( # ) # Begin { # Write-EnterFunction # } # Process { # $MyInvocation # } # End { # Write-LeaveFunction # } # } <# .SYNOPSIS Get the computer DNS domain name .DESCRIPTION .PARAMETER localhost request localhost's DNS domain .EXAMPLE $name = Get-ComputerDomain .NOTES This function comes from Dict.Windows module. #> function Get-ComputerDomain { [CmdletBinding()][OutputType([String])]Param ( ) Begin { Write-EnterFunction } Process { if (fileExist "Env:\USERDNSDOMAIN") { return $env:USERDNSDOMAIN } return 'localdomain' } End { Write-LeaveFunction } } <# .SYNOPSIS Get the computer SerialNumber .DESCRIPTION .PARAMETER localhost request localhost's SerialNumber .EXAMPLE $name = Get-ComputerSerialNumber .NOTES This function comes from Dict.Windows module. #> function Get-ComputerSerialNumber { [CmdletBinding()]Param ( ) Begin { Write-EnterFunction } Process { return (Get-CimInstance -ClassName Win32_BIOS).SerialNumber } End { Write-LeaveFunction } } <# .SYNOPSIS Get the computer manufacturer .DESCRIPTION .PARAMETER localhost request localhost's manufacturer .EXAMPLE $name = Get-ComputerManufacturer .NOTES This function comes from Dict.Windows module. #> function Get-ComputerManufacturer { [CmdletBinding()]Param ( ) Begin { Write-EnterFunction } Process { return (Get-CimInstance -ClassName Win32_BIOS).Manufacturer } End { Write-LeaveFunction } } <# .SYNOPSIS Get the computer Version .DESCRIPTION .PARAMETER localhost request localhost's Version .EXAMPLE $name = Get-ComputerVersion .NOTES This function comes from Dict.Windows module. #> function Get-ComputerVersion { [CmdletBinding()]Param ( ) Begin { Write-EnterFunction } Process { return (Get-CimInstance -ClassName Win32_BIOS).SMBIOSBIOSVersion } End { Write-LeaveFunction } } <# .SYNOPSIS Get the computer Model .DESCRIPTION .PARAMETER localhost request localhost's Model .EXAMPLE $name = Get-ComputerModel .NOTES This function comes from Dict.Windows module. #> function Get-ComputerModel { [CmdletBinding()]Param ( ) Begin { Write-EnterFunction } Process { # deprecated in Powershell Core # return (Get-WmiObject -Class:Win32_ComputerSystem).Model return (Get-CimInstance -ClassName Win32_ComputerSystem).Model } End { Write-LeaveFunction } } function Get-ComputerEthernet { [CmdletBinding()]Param ( [switch]$localhost, [ValidateSet('Index', 'Name')] [string]$ListAvailable = 'Index' ) Begin { Write-EnterFunction } Process { switch ($ListAvailable) { 'Index' { (Get-NetAdapter -Physical).ifIndex | Sort-Object # (Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration).Index | Sort-Object } 'Name' { # (Get-NetAdapter -IncludeHidden).Name | Sort-Object (Get-NetAdapter -Physical).Name | Sort-Object } } } End { Write-LeaveFunction } } <# .Synopsis Determines underlying firmware (BIOS) type and returns an integer indicating UEFI, Legacy BIOS or Unknown. Supported on Windows 8/Server 2012 or later .DESCRIPTION This function uses a complied Win32 API call to determine the underlying system firmware type. .EXAMPLE If (Get-ComputerFirmwareType -eq "UEFI") { # System is running UEFI firmware... } .EXAMPLE Switch (Get-ComputerFirmwareType) { "BIOS" { "Legacy BIOS" } "UEFI" { "UEFI" } Default { "Unknown" } } .OUTPUTS string "BIOS" or "UEFI" .FUNCTIONALITY Determines underlying system firmware type .LINK https://gallery.technet.microsoft.com/scriptcenter/Determine-UEFI-or-Legacy-7dc79488 .NOTES Author : Chris J Warwick https://social.technet.microsoft.com/profile/chris%20j%20warwick/ #> function Get-ComputerFirmwareType { [CmdletBinding()][OutputType([String])]Param ( # [switch]$localhost, # [string]$string = "" ) Begin { # eenter($MyInvocation.MyCommand) } Process { Add-Type -Language CSharp -TypeDefinition @' using System; using System.Runtime.InteropServices; 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' } } '@ $fw = "BIOS" $firmwareTypeNum = [FirmwareType]::GetFirmwareType() Switch ($firmwareTypeNum) { 1 { $fw = "BIOS" } 2 { $fw = "UEFI" } Default { $fw = "Unknown ($firmwareTypeNum)" } } return $fw } End { # eleave($MyInvocation.MyCommand) } } function Get-ComputerArch { [CmdletBinding()][OutputType([String])]Param ( [switch]$localhost, [string]$string = "" ) Begin { # eenter($MyInvocation.MyCommand) } Process { # found specs @url https://msdn.microsoft.com/en-us/library/aa394373(v=vs.85).aspx $value = (Get-CimInstance -ClassName CIM_Processor).DataWidth switch ($value) { 32 { return 'x86' } 64 { return 'x64' } else { return 'unknown' } } } End { # eleave($MyInvocation.MyCommand) } } <# ######## #### ###### ## ## ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ##### ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## #### ###### ## ## ###### #> function Get-ComputerDisks { [CmdletBinding()]Param ( [switch]$localhost, [ValidateSet('Index', 'Name')] [string]$ListAvailable = 'Index' ) Begin { Write-EnterFunction $precedence = @('Fixed') } Process { if ($Localhost) { foreach ($p in $precedence) { switch ($ListAvailable) { 'Index' { (Get-Disk | Where-Object { $_.ProvisioningType -eq $p }).Number } 'Name' { (Get-Disk | Where-Object { $_.ProvisioningType -eq $p }).UniqeId } } } } } End { Write-LeaveFunction } } function Get-ComputerDisks2 { [CmdletBinding( DefaultParameterSetName="ALL" )]Param( [switch]$localhost, [ValidateSet('Index', 'Name')] [string]$ListAvailable = 'Index', [Parameter(ParameterSetName="INDEX",ValueFromPipeLine = $true)] [int]$Index, [Parameter(ParameterSetName="NAME",ValueFromPipeLine = $true)] [string]$Name ) Begin { $disks = @() # precedence tell the order search precedence of the type of disk. It aims to mimic BIOS / UEFI discovery order $list = Get-Disk } Process { ForEach ($hash in $list) { $disk = $null # $disk = [PSCustomObject]@{ # Index = $i++ # Name = $d # serial = $lsblk.serial # uuid = $lsblk.uuid # manufacturer = $lsblk.vendor # model = $lsblk.model # PhysicalSectorSize = $lsblk."phy-sec" # size = ($lsblk.size.replace(',','.') + "B")/1 | Convert-Size -From Bytes -To Bytes -Precision 0 # PartitionStyle = "" # DriveType = "" # } $disk = @{} $disk.Index = $hash.Number $disk.name = $hash.FriendlyName $disk.serial = $hash.SerialNumber $disk.uuid = $hash.uuid $disk.manufacturer = $hash.Manufacturer $disk.model = $hash.Model $disk.PhysicalSectorSize = $hash.PhysicalSectorSize $disk.size = $hash.size | Convert-Size -From Bytes -To Bytes -Precision 0 $disk.PartitionStyle = $hash.PartitionStyle $disk.DriveType = "" switch ($hash.ProvisioningType) { 'Fixed' { $disk.DriveType = 'Fixed' } 'Removable' { $disk.DriveType = 'Removable' } } $disks += $disk } switch ($PSCmdlet.ParameterSetName) { 'INDEX' { return $disks[$Index] } 'NAME' { $Index = ($disks | Where-Object { $_.Name -eq $Name }).Index if ($null -ne $Index) { return $disks[$Index] } else { return } } 'ALL' { return $disks } } } End { } } function Get-DiskInfos { [CmdletBinding( DefaultParameterSetName="INDEX" )]Param( [switch]$localhost, [Parameter(ParameterSetName="INDEX",ValueFromPipeLine = $true)] [int]$DiskIndex, [Parameter(ParameterSetName="NAME",ValueFromPipeLine = $true)] [string]$DiskName ) Begin { # eenter($MyInvocation.MyCommand) } Process { switch ($PSCmdlet.ParameterSetName) { 'INDEX' { } 'NAME' { $DiskIndex = (Get-Disk | Where-Object { $_.UniqueId -eq $DiskName }).Number } } $disk = Get-Disk -Number $DiskIndex $obj = [PSCustomObject]@{ name = $disk.UniquId device = $disk.Path index = $disk.Number serial = $disk.SerialNumber uuid = $disk.Guid manufacturer = $disk.Manufacturer model = $disk.Model PhysicalSectorSize = $disk.PhysicalSectorSize default = $disk.IsBoot size = $disk.size PartitionStyle = $disk.PartitionStyle DriveType = $disk.ProvisioningType } return $obj } End { # eleave($MyInvocation.MyCommand) } } <# .SYNOPSIS List local disks .DESCRIPTION Fetch all informations available about local disks. .EXAMPLE An example .NOTES General notes #> <# .SYNOPSIS Convert a raw MSFT_Disk CIM instance into the normalized cross-platform disk object .DESCRIPTION Pure mapping function (no hardware access) turning one raw `Get-Disk` (MSFT_Disk) CIM instance into the normalized disk object shared by all operating systems. The raw instance is preserved untouched in the `raw` property. Sizes are already reported in bytes by the Storage provider. .EXAMPLE ConvertTo-ComputerDisk -Raw (Get-Disk)[0] -Index 0 .NOTES General notes #> function ConvertTo-ComputerDisk { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( # Raw MSFT_Disk CIM instance (Get-Disk) [Parameter(Mandatory = $true, ValueFromPipeline = $true)][object]$Raw, # 0-based position of the disk in the enumeration order [int]$Index ) Begin { Write-EnterFunction } Process { $path = "$($Raw.Path)" if (-not $path) { $path = "\\.\PHYSICALDRIVE$($Raw.Number)" } [PSCustomObject]@{ index = $Index name = "$($Raw.FriendlyName)" path = $path model = "$($Raw.Model)" vendor = "$($Raw.Manufacturer)" serial = "$($Raw.SerialNumber)" size = [long]$Raw.Size partitionStyle = "$($Raw.PartitionStyle)".ToLower() removable = "$($Raw.ProvisioningType)" -eq 'Removable' uuid = "$($Raw.UniqueId)" raw = $Raw } } End { Write-LeaveFunction } } <# .SYNOPSIS Convert a raw partition/volume hashtable into the normalized cross-platform partition object .DESCRIPTION Pure mapping function (no hardware access) turning one raw merged Get-Partition/Get-Volume hashtable into the normalized partition object shared by all operating systems. The raw hashtable is preserved untouched in the `raw` property. The uuid is the real partition Guid : it is left empty when the partition has none (no more fabricated random guid, which made the data non-deterministic). The usage statistics (`sizeUsed`, `sizeAvailable` in bytes and `usedPercent`) come from the volume fields merged into the raw hashtable (`Size`, `SizeRemaining`). They are `$null` when the partition has no volume (unformatted, metadata partition...). .EXAMPLE ConvertTo-ComputerPartition -Raw $partitionHash -DiskIndex 0 .NOTES General notes #> function ConvertTo-ComputerPartition { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( # Raw merged Get-Partition/Get-Volume hashtable [Parameter(Mandatory = $true, ValueFromPipeline = $true)][object]$Raw, # Index of the parent disk in the enumeration order [int]$DiskIndex ) Begin { Write-EnterFunction } Process { # volume usage statistics : SizeRemaining only exists in the merged # raw when the partition has a volume ; without one (unformatted, # metadata partition...) the fields stay $null. $sizeUsed = $null $sizeAvailable = $null $usedPercent = $null if ($null -ne $Raw.SizeRemaining) { $volumeSize = [long]$Raw.Size $sizeAvailable = [long]$Raw.SizeRemaining $sizeUsed = $volumeSize - $sizeAvailable if ($volumeSize -gt 0) { $usedPercent = [math]::Round([double]$sizeUsed / $volumeSize * 100, 1) } } [PSCustomObject]@{ diskIndex = $DiskIndex number = "$($Raw.PartitionNumber)" name = "Disk $($Raw.DiskNumber) Partition $($Raw.PartitionNumber)" path = "$($Raw.Path)" size = [long]$Raw.Size offset = [long]$Raw.Offset sizeUsed = $sizeUsed sizeAvailable = $sizeAvailable usedPercent = $usedPercent uuid = "$($Raw.Guid)" label = "$($Raw.FileSystemLabel)" fileSystem = "$($Raw.FileSystem)" mountpoint = "$($Raw.Mountpoint)" mountPoints = @($Raw.AccessPaths) bootable = [bool]$Raw.IsBoot system = [bool]$Raw.IsSystem children = @() raw = $Raw } } End { Write-LeaveFunction } } function Get-ComputerDisk { [CmdletBinding(DefaultParameterSetName = "ALL")] [OutputType([PSCustomObject])] Param ( # Disk index in the enumeration order [Parameter(Mandatory = $true, ParameterSetName = 'DISKNUMBER')][string]$DiskNumber, # Disk friendly name [Parameter(Mandatory = $true, ParameterSetName = 'DISKNAME')][string]$DiskName, # Full device address like in '\\.\PHYSICALDRIVE0' [Parameter(Mandatory = $true, ParameterSetName = 'DEVICE')][string]$Device, # Disk given its UniqueId [Alias('UniqueId')] [Parameter(Mandatory = $true, ParameterSetName = 'DISKID')][string]$DiskId, # Return all $disks [Parameter(Mandatory = $false, ParameterSetName = 'ALL')][switch]$All ) Begin { Write-EnterFunction $rawDisks = @(Get-Disk) $disks = @() $i = 0 foreach ($d in $rawDisks) { $disks += ConvertTo-ComputerDisk -Raw $d -Index $i $i++ } } Process { switch ($PSCmdlet.ParameterSetName) { 'DISKNUMBER' { $disks = @($disks | Where-Object { "$($_.index)" -eq $DiskNumber }) } 'DISKNAME' { $disks = @($disks | Where-Object { $_.name -eq $DiskName }) } 'DEVICE' { $disks = @($disks | Where-Object { $_.path -eq $Device }) } 'DISKID' { $disks = @($disks | Where-Object { $_.uuid -eq $DiskId }) } default { } } return $disks } End { Write-LeaveFunction } } <# .SYNOPSIS List local partitions .DESCRIPTION Fetch all informations available about local partitions. Linux lacks the 'Get-Partition' of the Storage module available on Windows. .EXAMPLE An example .NOTES General notes #> function Get-ComputerDiskPartition { [CmdletBinding(DefaultParameterSetName = "ALL")] [OutputType([PSCustomObject])] Param ( # Partition object [Parameter(Mandatory = $true, ValueFromPipeLine = $true, ParameterSetName = 'OBJECT')]$InputObject, # Partition with UUID [Alias('UniqueId')] [Parameter(Mandatory = $true, ParameterSetName = 'PARTUUID')][string]$PartUUID, # Label of the partition to mount [Alias('Label', 'PartitionLabel')] [Parameter(Mandatory = $true, ParameterSetName = 'PARTLABEL')][string]$PartLabel, # Disk index of the partition [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][uint32]$DiskNumber, # Partition number (can be several strings char since nvme disks. e.g. 'p1') [Alias('PartNum')] [Parameter(Mandatory = $false, ParameterSetName = 'DISKPART')][uint32]$PartitionNumber, # Full device address like in '\\?\Volume{...}' [Alias('Path')] [Parameter(Mandatory = $true, ParameterSetName = 'DEVICE')][string]$Device, # Mountpoint of a mounted partition [Alias('DriveLetter')] [Parameter(Mandatory = $true, ParameterSetName = 'MOUNTPOINT')][string]$Mountpoint, # Partition of the disk given its ID [Parameter(Mandatory = $true, ParameterSetName = 'DISKID')][string]$DiskId, # Return all partitions [Parameter(Mandatory = $false, ParameterSetName = 'ALL')][switch]$All ) Begin { Write-EnterFunction # fetch every partition, merge the volume informations (label, file # system, access paths...) into the raw hashtable, then map it to the # normalized cross-platform object # NOTE : the raw hashtable is built by direct PSObject.Properties # enumeration instead of ConvertTo-Hashtable/Merge-Hashtables (PwSh.Fw.Core) # because those helpers changed behavior between Core 1.x and 2.x for # CIM instances (which are IDictionary/IEnumerable), making the merge # unreliable. Direct enumeration keeps the native CIM values untouched. $partitions = @() foreach ($p in @(Get-Partition)) { # merge volume information to get partition label for example $vol = @(Get-Volume -Partition $p) $raw = @{} foreach ($source in @($p) + $vol) { if ($null -eq $source) { continue } foreach ($prop in $source.PSObject.Properties) { $raw[$prop.Name] = $prop.Value } } if ($raw.DriveLetter) { $raw.Mountpoint = "$($raw.DriveLetter):" } else { $raw.Mountpoint = $null } $raw.Mountpoints = $raw.AccessPaths $diskIndex = 0 if ($raw.DiskNumber) { $diskIndex = [int]$raw.DiskNumber } $partitions += ConvertTo-ComputerPartition -Raw $raw -DiskIndex $diskIndex } } Process { switch ($PSCmdlet.ParameterSetName) { 'OBJECT' { if ($InputObject.uuid) { $partitions = @($partitions | Where-Object { $_.uuid -eq $InputObject.uuid }) } else { $partitions = @($partitions | Where-Object { $_.diskIndex -eq $InputObject.diskIndex -and $_.number -eq $InputObject.number }) } } 'PARTUUID' { $partitions = @($partitions | Where-Object { $_.uuid -eq "$PartUUID" }) } 'PARTLABEL' { $partitions = @($partitions | Where-Object { $_.label -eq "$PartLabel" }) } 'DISKPART' { $partitions = @($partitions | Where-Object { $_.diskIndex -eq [int]$DiskNumber }) if ($PartitionNumber) { $partitions = @($partitions | Where-Object { $_.number -eq "$PartitionNumber" }) } } 'DEVICE' { $partitions = @($partitions | Where-Object { $_.path -like "$Device*" }) } 'MOUNTPOINT' { $partitions = @($partitions | Where-Object { $Mountpoint -in $_.mountPoints }) } 'DISKID' { $partitions = @($partitions | Where-Object { "$($_.raw.DiskId)" -eq "$DiskId" }) } default { } } return $partitions } End { Write-LeaveFunction } } <# .SYNOPSIS Find next available drive DriveLetter .DESCRIPTION List all drive letter already used and return the next one. It does not fill holes, it return the next letter of the far most one used. So if C: D: and G: are used, it will return H:, not E: .EXAMPLE Get-ComputerDiskNextAvailableDriveLetter .NOTES General notes #> function Get-ComputerDiskNextAvailableDriveLetter { [CmdletBinding()] [OutputType([char])] Param ( # [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$string ) Begin { Write-EnterFunction } Process { # one-liner return [char](([byte]((Get-Volume).DriveLetter | Sort-Object)[-1])+1) } End { Write-LeaveFunction } } <# .SYNOPSIS Mount a partition into running operating system .DESCRIPTION Mount specified partition .EXAMPLE An example .NOTES General notes .OUTPUTS [string] mountpoint #> function Mount-ComputerDiskPartition { [CmdletBinding()] [OutputType([String])] Param ( # Partition object [Parameter(Mandatory = $true, ValueFromPipeLine = $true, ParameterSetName = 'OBJECT')]$InputObject, # UUID of the partition to mount [Parameter(Mandatory = $true, ParameterSetName = 'PARTUUID')][string]$PartUuid, # Label of the partition to mount [Alias('Label', 'PartitionLabel')] [Parameter(Mandatory = $true, ParameterSetName = 'PARTLABEL')][string]$PartLabel, # Disk device name of the partition [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][uint32]$DiskNumber, # Partition number (can be several strings char since nvme disks. e.g. 'p1') [Alias('PartNum')] [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][uint32]$PartitionNumber, # Full device address like in '/dev/sda1' [Parameter(Mandatory = $true, ParameterSetName = 'DEVICE')][string]$Device, # options to pass [Parameter(Mandatory = $false)][string]$Options, # Unused here. For linux comatibility of Mount-ComputerDiskPartition [Parameter(Mandatory = $false)][switch]$Recurse, # force mounting to the mountpoint [Parameter(Mandatory = $false)][string]$Mountpoint, # Force mounting # If partition is already mounted, it will mount it to another mountpoint [Parameter(Mandatory = $false)][switch]$Force, # if specified, return the whole partition object, # else return only mountpoint [switch]$Passthru ) Begin { Write-EnterFunction } Process { switch ($PSCmdlet.ParameterSetName) { 'OBJECT' { $partition = $InputObject } 'PARTUUID' { $partition = Get-ComputerDiskPartition -PartUUID $PartUuid } 'PARTLABEL' { $partition = Get-ComputerDiskPartition -PartLabel $PartLabel } 'DISKPART' { $partition = Get-ComputerDiskPartition -DiskNumber $DiskNumber -PartitionNumber $PartitionNumber } 'DEVICE' { $partition = Get-ComputerDiskPartition -Device $Device } } if ($null -eq $partition) { return $null } # handle -Bind first because if it already mounted we do not have to remount it twice # deterministic mountpoint id : partition uuid, or diskIndex-number when absent $partitionId = $partition.uuid if (-not $partitionId) { $partitionId = "$($partition.diskIndex)-$($partition.number)" } if ($Force) { $Mountpoint = "$($env:ProgramData)\PwSh.Fw.Computer\Mountpoints\$partitionId\" $partition = Mount-ComputerDiskPartition -InputObject $partition -Mountpoint $Mountpoint -Passthru } # partition is already mounted ? return mountpoint # 1st case -> $Mountpoint not specified and Partition already mounted -> return # 2nd case -> $Mountpoint specified and partition already mounted -> check if partition is mounted on this specific mountpoint if ((!$Mountpoint) -and $partition.mountpoint) { Write-Debug "Partition $($partition.name) already mounted at '$($partition.mountpoint)'" if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $Mountpoint } } if ($Mountpoint -in $partition.mountPoints) { Write-Debug "Partition at Disk $($partition.diskIndex) Partition $($partition.number) already mounted at '$Mountpoint'" if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $Mountpoint } } if (!$Mountpoint) { $Mountpoint = "$($env:ProgramData)\PwSh.Fw.Computer\Mountpoints\$partitionId" } # auto add ":" char to single drive letter if ($Mountpoint.length -eq 1) { $Mountpoint += ":" } try { # NOTES on Add-PartitionAccessPath @https://learn.microsoft.com/en-us/powershell/module/storage/add-partitionaccesspath?view=windowsserver2022-ps#parameters # . Mounted folders are supported only on NTFS-formatted partitions. # . You can only assign a single drive letter to a partition. To change the drive letter, use the Set-Partition cmdlet with the NewDriveLetter parameter. if (${partition}?.fileSystem -eq 'NTFS') { $null = New-Item $Mountpoint -ItemType Directory -Force -ErrorAction SilentlyContinue Write-Devel "Add-PartitionAccessPath -DiskNumber $($partition.diskIndex) -PartitionNumber $($partition.number) -AccessPath $Mountpoint" # $null = Add-PartitionAccessPath -DiskNumber $partition.diskIndex -PartitionNumber $partition.number -AccessPath "$Mountpoint" $null = Add-PartitionAccessPath -DiskNumber [uint32]$partition.diskIndex -PartitionNumber [uint32]$partition.number -AccessPath "$Mountpoint" } else { # If partition already mounted on a drive letter, return it # return $partition.Mountpoint to return letter with colon if ($partition.raw.DriveLetter) { if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $partition.MountPoint } } else { Write-Devel "Add-PartitionAccessPath -DiskNumber $($partition.diskIndex) -PartitionNumber $($partition.number) -AssignDriveLetter" $Mountpoint = Add-PartitionAccessPath -DiskNumber [uint32]$partition.diskIndex -PartitionNumber [uint32]$partition.number -AssignDriveLetter } } } catch { Write-Error $_ return $null } if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $Mountpoint } } End { Write-LeaveFunction } } <# .SYNOPSIS Mount a partition into running operating system .DESCRIPTION Mount specified partition .EXAMPLE An example .NOTES General notes .OUTPUTS [string] mountpoint #> function DisMount-ComputerDiskPartition { [CmdletBinding(DefaultParameterSetName = 'OBJECT')] [OutputType([System.Boolean])] Param ( # Partition object [Parameter(Mandatory = $true, ValueFromPipeLine = $true, ParameterSetName = 'OBJECT')] [object]$InputObject, # UUID of the partition to mount [Parameter(Mandatory = $true, ParameterSetName = 'PARTUUID')][string]$PartUuid, # Label of the partition to mount [Alias('Label', 'PartitionLabel')] [Parameter(Mandatory = $true, ParameterSetName = 'PARTLABEL')][string]$PartLabel, # Disk device name of the partition [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][uint32]$DiskNumber, # Partition number (can be several strings char since nvme disks. e.g. 'p1') [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][uint32]$PartitionNumber, # Full device address like in '/dev/sda1' [Parameter(Mandatory = $true, ParameterSetName = 'DEVICE')][string]$Device, # Mountpoint of a mounted partition # A partition can have multiple mountpoints. # With a combination of -InputObject and -Mountpoint we can decide wich one to unmount [Alias('DriveLetter')] [Parameter(Mandatory = $false, ParameterSetName = 'OBJECT')] [Parameter(Mandatory = $true, ParameterSetName = 'MOUNTPOINT')] [string]$Mountpoint, # if specified, return the whole partition object, # else return only mountpoint [switch]$Passthru ) Begin { Write-EnterFunction } Process { switch ($PSCmdlet.ParameterSetName) { 'OBJECT' { $partition = $InputObject } 'PARTUUID' { $partition = Get-ComputerDiskPartition -PartUUID $PartUuid } 'PARTLABEL' { $partition = Get-ComputerDiskPartition -PartLabel $PartLabel } 'DISKPART' { $partition = Get-ComputerDiskPartition -DiskNumber $DiskNumber -PartitionNumber $PartitionNumber } 'MOUNTPOINT' { $partition = Get-ComputerDiskPartition -Mountpoint "$Mountpoint" } 'DEVICE' { $partition = Get-ComputerDiskPartition -Device $Device } } try { if (!$Mountpoint) { $Mountpoint = @($partition.mountPoints)[-1] } $p = Remove-PartitionAccessPath -DiskNumber [uint32]$partition.diskIndex -PartitionNumber [uint32]$partition.number -AccessPath "$Mountpoint" # if successful, remove folder $folder = Get-Item $Mountpoint -ErrorAction SilentlyContinue if ($folder.LinkType) { # folder is not a regular directory. Do not delete it } else { $null = Remove-Item $folder -Force } } catch { Write-Error $_ } $rc = $? if ($Passthru) { return $p } else { return $rc } } End { Write-LeaveFunction } } <# .SYNOPSIS Get the TPM (Trusted Platform Module) informations of this computer .DESCRIPTION Detect the TPM chip in three stages, the first one that answers wins : - stage 1 (source = "wmi") : WMI/CIM - Win32_Tpm (root/CIMV2) for chip presence - MSFT_TpmVersion, MSFT_TpmDevice and MSFT_TpmSupportedFeatures (root/CIMV2/Security/MicrosoftTpm) for version, state and vendor informations - stage 2 (source = "direct") : direct TPM 2.0 query through the TBS API (tbs.dll), used when WMI does not report a chip (Windows LTSC images without tpmcore.dll / Tpmsvc). See Get-ComputerTpmDirect. - stage 3 (source = "pnp") : the TPM PnP device (Win32_PnPEntity, Service = "TPM") as a last resort, reporting presence only. The object's 'source' property records which stage filled it. .EXAMPLE $tpm = Get-ComputerTpm .NOTES General notes #> function Get-ComputerTpm { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( ) Begin { Write-EnterFunction } Process { $tpm = New-ComputerTpmObject # stage 1 : WMI/CIM try { # chip presence $win32Tpm = Get-CimInstance -ClassName Win32_Tpm -ErrorAction Stop if ($win32Tpm -and $win32Tpm.TpmPresent) { $tpm.present = $true $namespace = "Root/CIMV2/Security/MicrosoftTpm" $tpmVersion = Get-CimInstance -Namespace $namespace -ClassName MSFT_TpmVersion -ErrorAction SilentlyContinue if ($tpmVersion) { $tpm.version = ConvertTo-TpmSpecVersion -InputObject $tpmVersion.TpmVersion } $tpmDevice = Get-CimInstance -Namespace $namespace -ClassName MSFT_TpmDevice -ErrorAction SilentlyContinue if ($tpmDevice) { $tpm.ready = [bool]$tpmDevice.IsReady $tpm.enabledOnBoot = [bool]$tpmDevice.IsEnabledOnBoot } $tpmFeatures = Get-CimInstance -Namespace $namespace -ClassName MSFT_TpmSupportedFeatures -ErrorAction SilentlyContinue if ($tpmFeatures) { $tpm.firmwareVersion = [string]$tpmFeatures.FirmwareVersion $tpm.vendor = [string]$tpmFeatures.VendorID $tpm.manufacturerInfo = [string]$tpmFeatures.ManufacturerInformation } $tpm.source = "wmi" return $tpm } } catch { Write-Debug "Get-ComputerTpm : wmi stage : $($_.Exception.Message)" } # stage 2 : direct TPM 2.0 query through TBS (tbs.dll) try { $direct = Get-ComputerTpmDirect if ($direct) { foreach ($property in $direct.PSObject.Properties) { $tpm.$($property.Name) = $property.Value } $tpm.source = "direct" return $tpm } } catch { Write-Debug "Get-ComputerTpm : direct stage : $($_.Exception.Message)" } # stage 3 : PnP device (presence only) try { $pnp = Get-CimInstance -ClassName Win32_PnPEntity -Filter "Service = 'TPM'" -ErrorAction SilentlyContinue | Select-Object -First 1 if ($pnp) { $tpm.present = $true if ($pnp.Manufacturer) { $tpm.vendor = [string]$pnp.Manufacturer } $tpm.devicePath = [string]$pnp.PNPDeviceID $tpm.source = "pnp" } } catch { Write-Debug "Get-ComputerTpm : pnp stage : $($_.Exception.Message)" } return $tpm } End { Write-LeaveFunction } } <# .SYNOPSIS Query a TPM 2.0 chip directly through the TBS API (tbs.dll) .DESCRIPTION Stage 2 of Get-ComputerTpm, for systems where WMI does not report a TPM (Windows LTSC images without tpmcore.dll / Tpmsvc). It talks to the chip through the Trusted Platform Module Base Services API (tbs.dll, present on every Windows 10+ system): - Tbsi_GetDeviceInfo reports chip presence and TPM version ; only TPM 2.0 chips are queried further. - Tbsip_Submit_Command issues TPM2_GetCapability (TPM_CAP_TPM_PROPERTIES) to read the specification revision, manufacturer id, vendor strings and firmware versions, and (best effort) TPM_CAP_ALGS for the supported hash algorithms. The GetCapability command is marshalled the way the tpm.sys driver validator expects it : a 22-octet body where the last two octets pad the property count up to four bytes (the classic 20-octet body is rejected with TPM_RC_INSUFFICIENT on tested builds). Returns $null when no TPM 2.0 chip is reachable through TBS. .EXAMPLE $tpm = Get-ComputerTpmDirect .NOTES General notes #> function Get-ComputerTpmDirect { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( ) Begin { Write-EnterFunction } Process { if (-not (Test-Path 'C:\Windows\System32\tbs.dll')) { return $null } if (-not ('PwSh.Fw.Computer.TbsApi' -as [type])) { $cs = @' using System; using System.Runtime.InteropServices; namespace PwSh.Fw.Computer { [StructLayout(LayoutKind.Sequential)] public struct TbsContextParams { public uint Version; public uint Flags; } public class TbsApi { [DllImport("tbs.dll", EntryPoint = "Tbsi_GetDeviceInfo")] public static extern int GetDeviceInfo(uint size, byte[] info); [DllImport("tbs.dll", EntryPoint = "Tbsi_Context_Create")] public static extern int ContextCreate(ref TbsContextParams ctxParams, out IntPtr ctx); [DllImport("tbs.dll", EntryPoint = "Tbsip_Submit_Command")] public static extern int SubmitCommand(IntPtr ctx, uint locality, uint priority, byte[] command, uint commandLength, byte[] response, ref uint responseLength); [DllImport("tbs.dll", EntryPoint = "Tbsip_Context_Close")] public static extern int ContextClose(IntPtr ctx); } } '@ Add-Type -TypeDefinition $cs -Language CSharp | Out-Null } $tbs = [PwSh.Fw.Computer.TbsApi] # chip presence and version $info = [byte[]]::new(16) $ret = $tbs::GetDeviceInfo(16, $info) if ($ret -ne 0) { return $null } # TBS_DEVICE_INFO is native endianness (unlike TPM command buffers) : # dwStructVersion(4) dwTpmVersion(4) dwInterfaceType(4) dwImplementationRevision(4) $tpmVersion = [System.BitConverter]::ToUInt32($info, 4) if ($tpmVersion -ne 2) { # direct access is limited to TPM 2.0 chips return $null } # context : version 2 (TPM 2.0 applications), flag 4 (IncludeTPM20) $ctxParams = [PwSh.Fw.Computer.TbsContextParams]::new() $ctxParams.Version = 2 $ctxParams.Flags = 4 $ctx = [IntPtr]::Zero $ret = $tbs::ContextCreate([ref]$ctxParams, [ref]$ctx) if ($ret -ne 0) { return $null } try { # TPM2_GetCapability(TPM_CAP_TPM_PROPERTIES, TPM_PT_FAMILY_INDICATOR, 8) # : the tpm.sys stack ignores property and count and returns # every fixed property $cmd = [byte[]]@(0x80, 0x01, 0, 0, 0, 22, 0, 0, 1, 0x7A, 0, 0, 0, 6, 0, 0, 0, 1, 0, 8, 0, 0) $resp = [byte[]]::new(4096) $rlen = [uint32]4096 $ret = $tbs::SubmitCommand($ctx, 0, 200, $cmd, [uint32]$cmd.Length, $resp, [ref]$rlen) if ($ret -ne 0) { return $null } $props = ConvertFrom-TpmTaggedProperties -Response $resp if ($props.Count -eq 0) { return $null } # TPM2_GetCapability(TPM_CAP_ALGS, 0, 32) : best effort $algCmd = [byte[]]@(0x80, 0x01, 0, 0, 0, 22, 0, 0, 1, 0x7A, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0) $algResp = [byte[]]::new(4096) $algLen = [uint32]4096 $ret = $tbs::SubmitCommand($ctx, 0, 200, $algCmd, [uint32]$algCmd.Length, $algResp, [ref]$algLen) $hashAlgorithms = @() if ($ret -eq 0) { $hashAlgorithms = @(ConvertFrom-TpmAlgList -Response $algResp) } } finally { [void]$tbs::ContextClose($ctx) } $firmwareVersion = ConvertFrom-TpmFirmwareVersion -Version1 ([uint32]$props[11]) -Version2 ([uint32]$props[12]) $vendor = ConvertFrom-TpmAscii4 -Value ([uint32]$props[5]) $manufacturerInfo = ( (ConvertFrom-TpmAscii4 -Value ([uint32]$props[6])) + (ConvertFrom-TpmAscii4 -Value ([uint32]$props[7])) + (ConvertFrom-TpmAscii4 -Value ([uint32]$props[8])) + (ConvertFrom-TpmAscii4 -Value ([uint32]$props[9])) ).Trim() # spec family from the chip's FAMILY_INDICATOR ("2.0"), falling # back to the TBS-reported major version (stage is 2.0 only) $family = ConvertFrom-TpmAscii4 -Value ([uint32]$props[0]) if (-not $family) { $family = '2' } # the chip answered : it is started and reachable return [PSCustomObject]@{ present = $true version = ConvertTo-TpmSpecVersion -InputObject $family firmwareVersion = $firmwareVersion vendor = $vendor manufacturerInfo = $manufacturerInfo ready = $true enabledOnBoot = $null devicePath = '\\.\TPM' hashAlgorithms = $hashAlgorithms } } End { Write-LeaveFunction } } <# .SYNOPSIS Read a big-endian 32-bit unsigned integer from a TPM command buffer .DESCRIPTION TPM commands and responses are network byte order (big endian). Returns 0 when the buffer is null or the offset out of range. .EXAMPLE Get-TpmU32 -Buffer $response -Offset 6 .NOTES General notes #> function Get-TpmU32 { [CmdletBinding()] [OutputType([Long])] Param ( [Parameter(Mandatory = $true)] [AllowNull()] [byte[]]$Buffer, [Parameter(Mandatory = $true)] [int]$Offset ) Begin { Write-EnterFunction } Process { if ($null -eq $Buffer -or ($Offset + 3) -gt $Buffer.Length) { return [long]0 } return [long]$Buffer[$Offset] * 16777216 + [long]$Buffer[$Offset + 1] * 65536 + [long]$Buffer[$Offset + 2] * 256 + [long]$Buffer[$Offset + 3] } End { Write-LeaveFunction } } <# .SYNOPSIS Parse a TPM2_GetCapability (TPM_CAP_TPM_PROPERTIES) response .DESCRIPTION Returns a hashtable mapping the fixed property index (relative to TPM2_PT_FIXED = 0x00000100) to its 32-bit value : 0 = family indicator, 1 = level, 2 = revision (x100), 3 = day of year, 4 = year, 5 = manufacturer id, 6-9 = vendor strings 1-4, 10 = vendor TPM type, 11-12 = firmware versions 1-2. Each property is a TPMS_TAGGED_PROPERTY : <property u32 BE><value u32 BE>, where property is 0x000001XX (group 1, the fixed properties). Two header framings are supported : - the framing used by the Windows tpm.sys driver, which adds one extra octet after the response code : capability at offset 11, count at 15, entries from 19 ; - the plain spec framing : capability at offset 10, count at 14, entries from 18. The framing is selected by the position of the capability field. Returns an empty hashtable when the response is not a successful TPM_CAP_TPM_PROPERTIES answer. .EXAMPLE $props = ConvertFrom-TpmTaggedProperties -Response $response .NOTES General notes #> function ConvertFrom-TpmTaggedProperties { [CmdletBinding()] [OutputType([Hashtable])] Param ( [Parameter(Mandatory = $true)] [AllowNull()] [byte[]]$Response ) Begin { Write-EnterFunction } Process { $props = @{} if ($null -ne $Response -and $Response.Length -ge 26 -and [int]$Response[0] * 256 + $Response[1] -eq 0x8001 -and (Get-TpmU32 -Buffer $Response -Offset 6) -eq 0) { # capability = 6 (TPM_CAP_TPM_PROPERTIES) selects the # framing : tpm.sys puts it at offset 11 (entries at 19), # the spec framing at offset 10 (entries at 18) foreach ($start in @(19, 18)) { if ((Get-TpmU32 -Buffer $Response -Offset ($start - 8)) -ne 6) { continue } $count = Get-TpmU32 -Buffer $Response -Offset ($start - 4) # sanity : a plausible count whose table fits the response # (one entry of slack for truncated answers) if ($count -le 0 -or $count -gt 512 -or $start + $count * 8 -gt $Response.Length + 8) { continue } for ($k = 0; $k -lt $count -and $start + $k * 8 + 7 -lt $Response.Length; $k++) { $prop = Get-TpmU32 -Buffer $Response -Offset ($start + $k * 8) # group 1 only : TPM2_PT_FIXED = 0x00000100 if ($prop -ge 0x00000100 -and $prop -lt 0x00000200) { $props[[int]($prop - 0x00000100)] = Get-TpmU32 -Buffer $Response -Offset ($start + $k * 8 + 4) } } break } } return $props } End { Write-LeaveFunction } } <# .SYNOPSIS Format the two TPM firmware version words as a dotted string .DESCRIPTION FIRMWARE_VERSION_1 packs major(16).minor(16), FIRMWARE_VERSION_2 packs build(16).patch(16). E.g. 0x00070002 / 0x00000001 becomes "7.2.0.1". Returns an empty string when both words are zero. .EXAMPLE ConvertFrom-TpmFirmwareVersion -Version1 0x00070002 -Version2 0x00000001 # => 7.2.0.1 .NOTES General notes #> function ConvertFrom-TpmFirmwareVersion { [CmdletBinding()] [OutputType([String])] Param ( [Parameter(Mandatory = $true)] [uint32]$Version1, [Parameter(Mandatory = $true)] [uint32]$Version2 ) Begin { Write-EnterFunction } Process { if ($Version1 -eq 0 -and $Version2 -eq 0) { return "" } $parts = @( [int]($Version1 / 65536), [int]($Version1 % 65536), [int]($Version2 / 65536), [int]($Version2 % 65536) ) return ($parts -join '.') } End { Write-LeaveFunction } } <# .SYNOPSIS Decode a 4-octet big-endian TPM property value as an ASCII string .DESCRIPTION Manufacturer ids and vendor strings are stored as four ASCII octets (NUL padded). Non printable octets are dropped. .EXAMPLE ConvertFrom-TpmAscii4 -Value 0x4E544300 # => NTC .NOTES General notes #> function ConvertFrom-TpmAscii4 { [CmdletBinding()] [OutputType([String])] Param ( [Parameter(Mandatory = $true)] [uint32]$Value ) Begin { Write-EnterFunction } Process { $s = '' for ($i = 3; $i -ge 0; $i--) { $b = [int](($Value / [Math]::Pow(256, $i)) % 256) if ($b -ge 32 -and $b -lt 127) { $s += [char]$b } } return $s.Trim() } End { Write-LeaveFunction } } <# .SYNOPSIS Parse a TPM2_GetCapability (TPM_CAP_ALGS) response into hash algorithm names .DESCRIPTION Maps the supported algorithm ids to their names, keeping only the hash algorithms usable as PCR banks : SHA1, SHA256, SHA384, SHA512, SM3_256, SHA3_256, SHA3_384, SHA3_512. Each algorithm is a TPMS_ALG_PROPERTY : <algId u16 BE><properties u32 BE>, and the two header framings (tpm.sys driver and plain spec) are handled like in ConvertFrom-TpmTaggedProperties. Returns an empty array when the response is not a successful TPM_CAP_ALGS answer. .EXAMPLE $algs = ConvertFrom-TpmAlgList -Response $response .NOTES General notes #> function ConvertFrom-TpmAlgList { [CmdletBinding()] [OutputType([String[]])] Param ( [Parameter(Mandatory = $true)] [AllowNull()] [byte[]]$Response ) Begin { Write-EnterFunction } Process { $names = [System.Collections.Generic.List[string]]::new() if ($null -ne $Response -and $Response.Length -ge 24 -and [int]$Response[0] * 256 + $Response[1] -eq 0x8001 -and (Get-TpmU32 -Buffer $Response -Offset 6) -eq 0) { $map = @{ 0x0004 = 'SHA1' 0x000B = 'SHA256' 0x000C = 'SHA384' 0x000D = 'SHA512' 0x0012 = 'SM3_256' 0x0027 = 'SHA3_256' 0x0028 = 'SHA3_384' 0x0029 = 'SHA3_512' } # capability = 0 (TPM_CAP_ALGS) : same dual framing as # ConvertFrom-TpmTaggedProperties (tpm.sys : capability at # offset 11, entries at 19 ; spec : offset 10, entries at 18) foreach ($start in @(19, 18)) { if ((Get-TpmU32 -Buffer $Response -Offset ($start - 8)) -ne 0) { continue } $count = Get-TpmU32 -Buffer $Response -Offset ($start - 4) # sanity : a plausible count whose table fits the response # (one entry of slack for truncated answers) if ($count -le 0 -or $count -gt 512 -or $start + $count * 6 -gt $Response.Length + 6) { continue } # TPML_ALG_PROPERTY : algId(2) properties(4) per entry for ($k = 0; $k -lt $count -and $start + $k * 6 + 5 -lt $Response.Length; $k++) { $o = $start + $k * 6 $algId = [int]$Response[$o] * 256 + $Response[$o + 1] if ($map.ContainsKey($algId) -and -not $names.Contains($map[$algId])) { $names.Add($map[$algId]) } } break } } # plain return : an empty list emits nothing, callers wrap with @() return $names.ToArray() } End { Write-LeaveFunction } } <# .SYNOPSIS Get the computer UUID .DESCRIPTION Read the SMBIOS UUID through CIM (Win32_ComputerSystemProduct). Returns an empty string when the UUID cannot be determined. .EXAMPLE $uuid = Get-ComputerUuid .NOTES General notes #> function Get-ComputerUuid { [CmdletBinding()] [OutputType([String])] Param ( ) Begin { Write-EnterFunction } Process { try { $uuid = (Get-CimInstance -ClassName Win32_ComputerSystemProduct -ErrorAction Stop).UUID if ($uuid) { return [string]$uuid } } catch { # no UUID reported by the platform : keep the default value Write-Debug "Get-ComputerUuid : $($_.Exception.Message)" } return "" } End { Write-LeaveFunction } } <# .SYNOPSIS Get the CPU informations of this computer .DESCRIPTION Read the CPU model and processor counts through CIM (Win32_Processor). The 'cores' property is the number of logical processors (SMT aware), the only count both platforms can reliably report ; 'physicalCores' is the number of physical cores. On multi-socket machines the values are summed over all sockets and the model name is the one of the first socket. .EXAMPLE $cpu = Get-ComputerCpu .NOTES General notes #> function Get-ComputerCpu { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( ) Begin { Write-EnterFunction } Process { $cpu = New-ComputerCpuObject try { $processors = @(Get-CimInstance -ClassName Win32_Processor -ErrorAction Stop) if ($processors.Count -gt 0) { $cpu.model = [string]$processors[0].Name # number of logical processors (SMT aware), summed over all sockets $cpu.cores = [int]($processors | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum # number of physical cores, summed over all sockets $cpu.physicalCores = [int]($processors | Measure-Object -Property NumberOfCores -Sum).Sum } } catch { # no processor information reported : keep the default object Write-Debug "Get-ComputerCpu : $($_.Exception.Message)" } return $cpu } End { Write-LeaveFunction } } <# .SYNOPSIS Get the total physical memory of this computer .DESCRIPTION Read TotalPhysicalMemory through CIM (Win32_ComputerSystem). Returns 0 when the value cannot be determined. .EXAMPLE $memory = Get-ComputerMemory .NOTES General notes #> function Get-ComputerMemory { [CmdletBinding()] [OutputType([Int64])] Param ( ) Begin { Write-EnterFunction } Process { try { $totalPhysicalMemory = (Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop).TotalPhysicalMemory if ($totalPhysicalMemory) { return [Int64]$totalPhysicalMemory } } catch { # no memory information reported : keep the default value Write-Debug "Get-ComputerMemory : $($_.Exception.Message)" } return [Int64]0 } End { Write-LeaveFunction } } <# .SYNOPSIS Get the uptime of this computer .DESCRIPTION Compute the time elapsed since LastBootUpTime through CIM (Win32_OperatingSystem), in seconds. CimInstance hands LastBootUpTime back as an already-converted local [datetime] (the raw DMTF string is only converted on demand), so both shapes are handled. Returns 0 when the value cannot be determined. .EXAMPLE $uptime = Get-ComputerUptime .NOTES General notes #> function Get-ComputerUptime { [CmdletBinding()] [OutputType([Double])] Param ( ) Begin { Write-EnterFunction } Process { try { $lastBootUpTime = (Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime if ($lastBootUpTime) { # Get-CimInstance already converts the CIM datetime to a # local [datetime] ; the raw DMTF string only appears when # reading an unconverted property, so both shapes are handled if ($lastBootUpTime -is [string]) { $boot = [Management.ManagementDateTimeConverter]::ToDateTime($lastBootUpTime) } else { $boot = [datetime]$lastBootUpTime } return ((Get-Date) - $boot).TotalSeconds } } catch { # no boot time reported : keep the default value Write-Debug "Get-ComputerUptime : $($_.Exception.Message)" } return [double]0 } End { Write-LeaveFunction } } |