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 through 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
 
.EXAMPLE
$tpm = Get-ComputerTpm
 
.NOTES
General notes
#>

function Get-ComputerTpm {
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    Param (
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        $tpm = New-ComputerTpmObject
        try {
            # chip presence
            $win32Tpm = Get-CimInstance -ClassName Win32_Tpm -ErrorAction Stop
            if ($win32Tpm.TpmPresent -eq $false) {
                return $tpm
            }
            $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
            }
        } catch {
            # no TPM support on this system : keep the default (present = $false) object
            $tpm = New-ComputerTpmObject
        }
        return $tpm
    }

    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
    }
}