Dictionaries/Computer.Dict.Linux/Computer.Dict.Linux.psm1
|
<#
###### ####### ## ## ######## ## ## ######## ######## ######## ## ## ## ## ### ### ## ## ## ## ## ## ## ## ## ## ## #### #### ## ## ## ## ## ## ## ## ## ## ## ## ### ## ######## ## ## ## ###### ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ####### ## ## ## ####### ## ######## ## ## #> # function Get-MyInvocation { # [CmdletBinding()] # [OutputType([String])] # Param ( # ) # Begin { # Write-EnterFunction # } # Process { # $MyInvocation # } # End { # Write-LeaveFunction # } # } function Get-ComputerDomain { hostname -d } function Get-ComputerManufacturer { [CmdletBinding()][OutputType([String])]Param ( ) Begin { Write-EnterFunction } Process { return (New-HashtableFromCommand -Command "dmidecode | awk '/^System Information/,/^$/'" -sep ":" -SkipFirstLines 1).manufacturer } End { Write-LeaveFunction } } function Get-ComputerModel { [CmdletBinding()]Param ( ) Begin { Write-EnterFunction } Process { return (dmidecode | awk '/^System Information/,/^$/' | Select-Object -Skip 1 | ConvertFrom-StringData -Delimiter ":")."product name" # return (New-HashtableFromCommand -Command "dmidecode | awk '/^System Information/,/^$/'" -sep ":" -SkipFirstLines 1)."product name" } End { Write-LeaveFunction } } function Get-ComputerSerialNumber { [CmdletBinding()]Param ( ) Begin { Write-EnterFunction } Process { return (New-HashtableFromCommand -Command "dmidecode | awk '/^System Information/,/^$/'" -sep ":" -SkipFirstLines 1)."serial number" } End { Write-LeaveFunction } } <# .SYNOPSIS Know if computer was booted using old legacy BIOS mode or new UEFI. .DESCRIPTION To make next boot efficient, we need to know in what mode the computer booted to this stage. This function will tell us that. If every tests fail, or if we can't determined the boot mode, it defaults to "BIOS" mode. .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" .NOTES General notes #> function Get-ComputerFirmwareType { [CmdletBinding()] [OutputType([String])] Param ( # [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$string ) Begin { Write-EnterFunction } Process { $bootMode = "BIOS" if (Test-DirExist "/sys/firmware/efi") { $bootMode = "UEFI" } return $bootMode } End { Write-LeaveFunction } } <# ######## #### ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ##### ## ## ## ## ## ## ## ## ## ## ## ## ## ######## #### ###### ## ## #> <# .SYNOPSIS List local disks .DESCRIPTION Fetch all informations available about local disks. Linux lacks the 'Get-Disk' of the Storage module available on Windows. .EXAMPLE An example .NOTES General notes #> <# .SYNOPSIS Convert a raw lsblk disk entry into the normalized cross-platform disk object .DESCRIPTION Pure mapping function (no hardware access) turning one raw `lsblk --json` block device entry (type=disk) into the normalized disk object shared by all operating systems. The raw entry is preserved untouched in the `raw` property. Sizes are numeric bytes because the collection uses `lsblk -b`. .EXAMPLE ConvertTo-ComputerDisk -Raw $lsblkEntry -Index 0 .NOTES General notes #> function ConvertTo-ComputerDisk { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( # Raw lsblk block device entry (type=disk) [Parameter(Mandatory = $true, ValueFromPipeline = $true)][object]$Raw, # 0-based position of the disk in the enumeration order [int]$Index ) Begin { Write-EnterFunction } Process { $partitionStyle = "$($Raw.pttype)".ToLower() switch ($partitionStyle) { 'dos' { $partitionStyle = 'mbr' } } [PSCustomObject]@{ index = $Index name = "$($Raw.name)" path = "$($Raw.path)" model = "$($Raw.model)" vendor = "$($Raw.vendor)" serial = "$($Raw.serial)" size = [long]$Raw.size partitionStyle = $partitionStyle removable = [bool]$Raw.rm uuid = "$($Raw.ptuuid)" raw = $Raw } } End { Write-LeaveFunction } } <# .SYNOPSIS Convert a raw lsblk partition entry into the normalized cross-platform partition object .DESCRIPTION Pure mapping function (no hardware access) turning one raw `lsblk --json` entry (type=part or nested device such as a LUKS volume) into the normalized partition object shared by all operating systems. The raw entry is preserved untouched in the `raw` property. Nested devices (children) are mapped recursively. The offset is computed in bytes from the starting sector and the logical sector size. The bootable flag is derived from the MBR partflags (0x80 bit). The usage statistics (`sizeUsed`, `sizeAvailable` in bytes and `usedPercent`) come from the filesystem fields reported by lsblk (`fsused`, `fsavail`, `fsuse%`). They are `$null` when the partition has no filesystem (LUKS container, unformatted partition...). .EXAMPLE ConvertTo-ComputerPartition -Raw $lsblkEntry -DiskIndex 0 .NOTES General notes #> function ConvertTo-ComputerPartition { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( # Raw lsblk block device entry (type=part or nested device) [Parameter(Mandatory = $true, ValueFromPipeline = $true)][object]$Raw, # Index of the parent disk in the enumeration order [int]$DiskIndex ) Begin { Write-EnterFunction } Process { # MBR bootable flag (0x80 bit of partflags). lsblk can also report # named flags (GPT) instead of a hex value : only a 0x-prefixed hex # token is parsed, so the conversion below cannot fail. $bootable = $false if ("$($Raw.partflags)" -match '(0x[0-9a-fA-F]+)') { $bootable = ([Convert]::ToInt64($Matches[1], 16) -band 0x80) -ne 0 } # byte offset from starting sector x logical sector size $offset = 0 if ($null -ne $Raw.start) { $offset = [long]$Raw.start * [long]$Raw."log-sec" } # filesystem usage statistics : lsblk -b reports them as numeric # bytes. Partitions without a filesystem (LUKS container, unformatted # partition...) have none, so the fields stay $null. $sizeUsed = $null if ($null -ne $Raw.fsused) { $sizeUsed = [long]$Raw.fsused } $sizeAvailable = $null if ($null -ne $Raw.fsavail) { $sizeAvailable = [long]$Raw.fsavail } $usedPercent = $null if ("$($Raw.'fsuse%')" -match '^(\d+(?:\.\d+)?)\s*%?$') { # use the percentage as reported by the OS itself (like df) $usedPercent = [double]$Matches[1] } elseif ($null -ne $Raw.fsused -and [long]$Raw.fssize -gt 0) { # no fsuse% reported : compute it from the raw byte counters $usedPercent = [math]::Round([double]$sizeUsed / [long]$Raw.fssize * 100, 1) } [PSCustomObject]@{ diskIndex = $DiskIndex number = "$($Raw.partn)" name = "$($Raw.kname)" path = "$($Raw.path)" size = [long]$Raw.size offset = $offset sizeUsed = $sizeUsed sizeAvailable = $sizeAvailable usedPercent = $usedPercent uuid = "$($Raw.partuuid)" label = "$($Raw.label)" fileSystem = "$($Raw.fstype)" mountpoint = "$($Raw.mountpoint)" mountPoints = @($Raw.mountpoints) bootable = $bootable system = $false children = @( @($Raw.children) | Where-Object { $null -ne $_ } | ForEach-Object { ConvertTo-ComputerPartition -Raw $_ -DiskIndex $DiskIndex } ) 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 device name (without /dev) [Parameter(Mandatory = $true, ParameterSetName = 'DISKNAME')][string]$DiskName, # Full device address like in '/dev/sda' [Parameter(Mandatory = $true, ParameterSetName = 'DEVICE')][string]$Device, # Partition of the disk given its ID [Alias('UniqueId')] [Parameter(Mandatory = $true, ParameterSetName = 'DISKID')][string]$DiskId, # Return all $disks [Parameter(Mandatory = $false, ParameterSetName = 'ALL')][switch]$All ) Begin { Write-EnterFunction # -b makes lsblk report sizes as numeric bytes in the JSON output $rawDisks = ((lsblk -b --output-all --json --tree) | ConvertFrom-Json).blockdevices | Where-Object { $_.type -eq "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 device name of the partition [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][string]$Disk, # Partition number (can be several strings char since nvme disks. e.g. 'p1') [Alias('PartitionNumber')] [Parameter(Mandatory = $false, ParameterSetName = 'DISKPART')][string]$PartNum, # Full device address like in '/dev/sda1' [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 $disks = @(Get-ComputerDisk -All) # flatten the direct children of every disk into normalized partitions # (disks without partitions have no children : nothing to add) $partitions = @() foreach ($d in $disks) { foreach ($c in @($d.raw.children) | Where-Object { $null -ne $_ }) { $partitions += ConvertTo-ComputerPartition -Raw $c -DiskIndex $d.index } } } Process { switch ($PSCmdlet.ParameterSetName) { 'OBJECT' { $partitions = @($partitions | Where-Object { $_.uuid -eq $InputObject.uuid }) } 'PARTUUID' { $partitions = @($partitions | Where-Object { $_.uuid -eq "$PartUUID" }) } 'PARTLABEL' { $partitions = @($partitions | Where-Object { $_.label -eq "$PartLabel" }) } 'DISKPART' { $diskIndex = @($disks | Where-Object { $_.name -eq $Disk })[0].index $partitions = @($partitions | Where-Object { $_.diskIndex -eq $diskIndex }) if ($PartNum) { $partitions = @($partitions | Where-Object { $_.number -eq "$PartNum" }) } } 'DEVICE' { $partitions = @($partitions | Where-Object { $_.path -like "$Device*" }) } 'MOUNTPOINT' { $partitions = @($partitions | Where-Object { $Mountpoint -in $_.mountPoints }) } 'DISKID' { $partitions = @($partitions | Where-Object { $_.raw.ptuuid -eq "$DiskId" }) } default { } } return $partitions } 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], [array])] 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')][string]$Disk, # Partition number (can be several strings char since nvme disks. e.g. 'p1') [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][string]$PartNum, # Full device address like in '/dev/sda1' [Parameter(Mandatory = $true, ParameterSetName = 'DEVICE')][string]$Device, # options to pass [Parameter(Mandatory = $false)][string]$Options, # Recurse through partition children [Parameter(Mandatory = $false)][switch]$Recurse, # Specify mounting to this mountpoint [Parameter(Mandatory = $false)][string]$Mountpoint, # 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 -Disk $Disk -PartNum $PartNum } 'DEVICE' { $partition = Get-ComputerDiskPartition -Device $Device } } # 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 = "/var/lib/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 -> $Mountpoit specified and partition already mounted -> check if partition is mounted on this specific mountpoit if ((!$Mountpoint) -and $partition.mountpoint) { Write-Debug "Partition $($partition.name) already mounted at '$Mountpoint'" if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $Mountpoint } } if ($Mountpoint -in $partition.mountPoints) { Write-Debug "Partition $($partition.name) already mounted at '$Mountpoint'" if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $Mountpoint } } if ($partition.children) { if ($Recurse) { $Mountpoints = @() foreach ($c in $partition.children) { $Mountpoints += Mount-ComputerDiskPartition -InputObject $c -Recurse } if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $Mountpoint } } else { Write-Warning "Partition $($partition.name) have children (subvolumes). You may want to mount those volumes instead." Write-Warning "Use -Recurse to mount subvolumes automatically." return $null } } if (!$Mountpoint) { # $Mountpoint = "/mnt/$($partition.name)" $Mountpoint = "/var/lib/pwsh.fw.computer/mountpoints/$partitionId" } $rc = New-Item $Mountpoint -ItemType Directory -Force Write-Debug "Mount partition $($partition.name) in $Mountpoint" # options is an array of comma separated values $aOptions = $Options -split "," switch ($partition.fileSystem) { 'ntfs' { # probe for mountability $rc = Execute-Command -exe ntfs-3g.probe -args "--readwrite $($partition.path)" -AsBool rc=$? switch (${rc}) { 14 { Write-Warning "Windows is hibernating, ntfs-3g will refuse to mount it." Write-Warning "We'll try to mount removing hiberfile" # if ${options} is defined, then OPTIONS="${options},ro" else, OPTIONS="ro" $aOptions += "remove_hiberfile" } } # Make sure the dirty flag is removed. If not, mounting the NTFS partition is impossible. $rc = Execute-Command -exe ntfsfix -args "-d $($partition.path)" # if ${options} is defined, then OPTIONS="-o ${options}" else, OPTIONS="" $rc = Execute-Command -exe ntfs-3g -args "$($partition.path) $MountPoint $($aOptions -join ",")" } 'crypto_LUKS' { $passPhrase = Write-Question -Prompt "Please enter pass-phrase to decypher partition $($partition.name)" $rc = Execute-Command -exe "cryptsetup" -args "luksOpen $($partition.path) $($partition.name) - <<< ${passPhrase}" # if [ -e /dev/mapper/${part} ]; then # $mountPoint=$(MountPartition /dev/mapper/${part}) # return $(true) # else # CLog "ERR" "${FUNCNAME}(): failed to unlock luks partition /dev/${part}" # return $(false) # fi } 'swap' { # Do nothing, we do not mount swap. Write-Warning "Partition $($partition.name) is a SWAP partition. Skip it." } Default { # if partition already have a mountpoint, use another mount syntax if ($Force) { $rc = Execute-Command -exe mount -args "--bind $($partition.mountpoint) $MountPoint $($aOptions -join ",")" } else { $rc = Execute-Command -exe mount -args "-t auto $($partition.path) $MountPoint $($aOptions -join ",")" } } } if ($Passthru) { return Get-ComputerDiskPartition -InputObject $partition } else { return $Mountpoint } } End { Write-LeaveFunction } } <# .SYNOPSIS Get the TPM (Trusted Platform Module) informations of this computer .DESCRIPTION Detect the TPM chip through the kernel sysfs interfaces : - /sys/class/tpm/tpm<N> : TPM 2.0 kernel driver - /sys/class/misc/tpm<N> : legacy TPM 1.2 kernel driver When tpm2-tools is installed and the chip is reachable, the result is enriched with the chip vendor and firmware version. .EXAMPLE $tpm = Get-ComputerTpm .NOTES General notes #> function Get-ComputerTpm { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( ) Begin { Write-EnterFunction } Process { $tpm = New-ComputerTpmObject # The TPM 2.0 kernel driver exposes /sys/class/tpm/tpm<N> $tpmSysfs = Get-ChildItem "/sys/class/tpm" -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "tpm*" } | Select-Object -First 1 if ($tpmSysfs) { $tpm.present = $true $tpm.version = "2.0" # read the major version when the kernel exposes it $majorFile = Join-Path $tpmSysfs.FullName "tpm_version_major" if (Test-Path $majorFile) { $tpm.version = ConvertTo-TpmSpecVersion -InputObject (Get-Content $majorFile -Raw).Trim() } # device name from uevent, fallback to the sysfs entry name $ueventFile = Join-Path $tpmSysfs.FullName "uevent" if (Test-Path $ueventFile) { $devname = (Get-Content $ueventFile | Where-Object { $_ -like "DEVNAME=*" } | Select-Object -First 1) -replace '^DEVNAME=' if ($devname) { $tpm.devicePath = "/dev/$devname" } } if (-not $tpm.devicePath) { $tpm.devicePath = "/dev/$($tpmSysfs.Name)" } # hash algorithms supported by the TPM, exposed as pcr-* directories $tpm.hashAlgorithms = @( Get-ChildItem $tpmSysfs.FullName -Directory -Filter "pcr-*" -ErrorAction SilentlyContinue | ForEach-Object { ConvertTo-TpmHashAlgorithm -InputObject $_.Name } ) } else { # The legacy TPM 1.2 kernel driver exposes /sys/class/misc/tpm<N> $tpmSysfs = Get-ChildItem "/sys/class/misc" -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "tpm*" } | Select-Object -First 1 if ($tpmSysfs) { $tpm.present = $true $tpm.version = "1.2" $tpm.devicePath = "/dev/$($tpmSysfs.Name)" } } # probe the chip : reading /dev/tpm0 requires access rights (root or tss group) if ($tpm.present) { $tpm2Getrandom = Get-Command tpm2_getrandom -ErrorAction SilentlyContinue if ($tpm2Getrandom) { $null = tpm2_getrandom 4 2>$null $tpm.ready = ($LASTEXITCODE -eq 0) # enrich with chip properties when we can actually talk to the chip if ($tpm.ready) { $tpm2Getproperty = Get-Command tpm2_getproperty -ErrorAction SilentlyContinue if ($tpm2Getproperty) { $properties = @(& tpm2_getproperty --family=2.0 --list 2>$null) if ($LASTEXITCODE -eq 0) { foreach ($line in $properties) { if ($line -match '^\s*([\w-]+)\s*:\s*(.+?)\s*$') { switch ($matches[1]) { "vendor" { $tpm.vendor = $matches[2] } "firmware-version" { $tpm.firmwareVersion = $matches[2] } } } } } } } } } return $tpm } End { Write-LeaveFunction } } <# .SYNOPSIS Get the computer UUID .DESCRIPTION Read the SMBIOS product UUID from the kernel sysfs interface (/sys/class/dmi/id/product_uuid). When the file is not readable (e.g. root-only permissions), fall back to dmidecode. 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 { # primary source : kernel sysfs $uuidFile = "/sys/class/dmi/id/product_uuid" if (Test-Path $uuidFile) { try { $uuid = (Get-Content $uuidFile -Raw -ErrorAction Stop).Trim() if ($uuid) { return $uuid } } catch { # not readable (e.g. root-only permissions) : try dmidecode Write-Debug "Get-ComputerUuid : cannot read $uuidFile : $($_.Exception.Message)" } } # fallback : dmidecode (needs root or CAP_SYS_RAWIO) $dmidecode = Get-Command dmidecode -ErrorAction SilentlyContinue if ($dmidecode) { $uuid = & dmidecode -s system-uuid 2>$null if ($LASTEXITCODE -eq 0 -and $uuid) { return "$uuid".Trim() } } return "" } End { Write-LeaveFunction } } <# .SYNOPSIS Get the CPU informations of this computer .DESCRIPTION Read the CPU model and processor counts from /proc/cpuinfo (one section per logical processor). The 'cores' property is the number of logical processors (SMT aware), the only count both platforms can reliably report ; 'physicalCores' is filled when the platform exposes the physical topology (physical id / core id). When the fields are missing (e.g. some architectures), fall back to lscpu. .EXAMPLE $cpu = Get-ComputerCpu .NOTES General notes #> function Get-ComputerCpu { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( ) Begin { Write-EnterFunction } Process { $cpu = New-ComputerCpuObject # primary source : /proc/cpuinfo (one section per logical processor) $cpuInfoFile = "/proc/cpuinfo" if (Test-Path $cpuInfoFile) { $lines = @(Get-Content $cpuInfoFile) # model name of the first processor ("model name" on x86, "Model" on arm) $modelLine = $lines | Where-Object { $_ -match '^\s*model name\s*:' } | Select-Object -First 1 if (-not $modelLine) { $modelLine = $lines | Where-Object { $_ -match '^\s*Model\s*:' } | Select-Object -First 1 } if ($modelLine) { $cpu.model = ($modelLine -split ':\s*', 2)[1].Trim() } # number of logical processors $cpu.cores = @($lines | Where-Object { $_ -match '^\s*processor\s*:' }).Count # physical cores : unique (physical id, core id) pairs when exposed $corePairs = New-Object System.Collections.Generic.HashSet[string] $physicalId = $null $coreId = $null foreach ($line in $lines) { if ($line -match '^\s*physical id\s*:\s*(\S+)') { $physicalId = $matches[1] } elseif ($line -match '^\s*core id\s*:\s*(\S+)') { $coreId = $matches[1] } elseif ($line.Trim() -eq '') { # blank line ends a processor section if (($null -ne $physicalId) -and ($null -ne $coreId)) { [void]$corePairs.Add("${physicalId}:${coreId}") } $physicalId = $null $coreId = $null } } # the last section is not followed by a blank line if (($null -ne $physicalId) -and ($null -ne $coreId)) { [void]$corePairs.Add("${physicalId}:${coreId}") } if ($corePairs.Count -gt 0) { $cpu.physicalCores = $corePairs.Count } } # fallback : lscpu when /proc/cpuinfo did not provide the data # (force the C locale, lscpu labels are localized otherwise) if ((-not $cpu.model) -or ($cpu.cores -eq 0)) { $lscpu = Get-Command lscpu -ErrorAction SilentlyContinue if ($lscpu) { $previousLocale = $env:LC_ALL $env:LC_ALL = "C" try { $lscpuOutput = @(& lscpu 2>$null) if ($LASTEXITCODE -eq 0) { if (-not $cpu.model) { $modelLine = $lscpuOutput | Where-Object { $_ -match '^Model name\s*:' } | Select-Object -First 1 if ($modelLine) { $cpu.model = ($modelLine -split ':\s*', 2)[1].Trim() } } if ($cpu.cores -eq 0) { $cpusLine = $lscpuOutput | Where-Object { $_ -match '^CPU\(s\)\s*:' } | Select-Object -First 1 if ($cpusLine) { $count = ($cpusLine -split ':\s*', 2)[1].Trim() if ($count -match '^\d+$') { $cpu.cores = [int]$count } } } } } finally { $env:LC_ALL = $previousLocale } } } return $cpu } End { Write-LeaveFunction } } <# .SYNOPSIS Get the total physical memory of this computer .DESCRIPTION Read MemTotal from /proc/meminfo (in kB) and convert it to bytes. 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 { $memInfoFile = "/proc/meminfo" if (Test-Path $memInfoFile) { $line = Get-Content $memInfoFile | Where-Object { $_ -match '^\s*MemTotal\s*:' } | Select-Object -First 1 if ($line) { # "MemTotal: 32500252 kB" $fields = $line -split '\s+' if ($fields.Count -ge 2 -and $fields[1] -match '^\d+$') { return [Int64]$fields[1] * 1024 } } } return [Int64]0 } End { Write-LeaveFunction } } <# .SYNOPSIS Get the uptime of this computer .DESCRIPTION Read the system uptime in seconds from the first field of /proc/uptime. 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 { $uptimeFile = "/proc/uptime" if (Test-Path $uptimeFile) { $seconds = $null $value = (Get-Content $uptimeFile -Raw).Trim().Split(' ')[0] if ([double]::TryParse($value, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$seconds)) { return $seconds } } return [double]0 } End { Write-LeaveFunction } } |