OpsaC - Operating as PowerShell code
published: March 14, 2024 author: Tinu tags: PowerShell - News categories: PowerShell-Cross-Platform
The magic differents of Mac, Linux and Windows if you working with PowerShell.
I didn’t find any commands for Cross-Platform usage to get the OS-Information.
On Windows you can use the CIM-Class Win32_OperatingSystem to get some information of the current installed os:
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -ExpandProperty Caption
Microsoft Windows Server 2019 Datacenter
On Linux you can use the /etc/os-release file to get some information of the current installed os:
$OsString = cat /etc/os-release | grep PRETTY_NAME
[regex]::Match($OsString, '\w+\s\d+\.\d+').value
Red Hat Enterprise Linux 9.1
On a Mac OS you can use either sw_vers or system_profiler to get some information of the current installed os:
$OsString = sw_vers -productName && sw_vers -productVersion && sw_vers -buildVersion
"$($OsString[0]) $($OsString[1]) $($OsString[2])"
macOS 13.6.7 22G720
$OsString = system_profiler SPSoftwareDataType
[regex]::Match($OsString, '\w+\s\d+\.\d+\.\d+\s\(\d+\w+\)').value
macOS 13.6.7 (22G720)
You can use the command whoami to get the current username or the command hostname to get the current Computername, but there are other ways to get this information.
whoami
hostname
The same as on Mac and Linux, but in PowerShell we use the following commands:
$env:USERNAME
$env:COMPUTERNAME
The better way as using whoami and hostname and the Windows-only-commands is to use the DotNet-Method:
[Environment]::UserName
[Environment]::MachineName
[Environment]::UserDomainName
This commands lists all the environment variables in the current session:
Drive Provider:
Get-Item Env:
.Net Method:
[Environment]::GetEnvironmentVariables()
Test is the current user is administrator or on Mac and Linux is root:
$currentUser = (id -u)
$IsAdmin = ($currentUser -eq 0)
$currentUser = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$IsAdmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
Split the path of the PSModulePath environment variable:
$env:PSModulePath -split ':'
$env:PSModulePath -split ';'
If you using the [System.IO.Path]::PathSeparator
, then you get the PSModulePath splitted on each Operating System.
$env:PSModulePath -split [System.IO.Path]::PathSeparator
On Mac
/Users/xxx/.local/share/powershell/Modules
/usr/local/share/powershell/Modules
/usr/local/microsoft/powershell/7/Modules
On AlmaLinux
/Users/xxx/.local/share/powershell/Modules
/usr/local/share/powershell/Modules
/opt/microsoft/powershell/7/Modules
Read from the hosts-file:
$Path = "$($env:windir)\system32\drivers\etc\hosts"
Get-Content $Path
$Path = "/etc/hosts"
Get-Content $Path
Get the Temp-path:
$env:tmp
[System.IO.Path]::GetTempPath()