0
0
PowerShellscripting~5 mins

Platform-specific considerations in PowerShell

Choose your learning style9 modes available
Introduction
Different computers and systems work in different ways. Knowing platform-specific details helps your script run correctly everywhere.
You want your script to work on Windows and Linux computers.
You need to handle file paths that look different on each system.
You want to run commands that only exist on one platform.
You want to check the system type before doing something special.
You want to avoid errors caused by platform differences.
Syntax
PowerShell
if ($IsWindows) {
    # Windows-specific code
} elseif ($IsLinux) {
    # Linux-specific code
} elseif ($IsMacOS) {
    # macOS-specific code
}
PowerShell has automatic variables like $IsWindows, $IsLinux, and $IsMacOS to detect the platform.
Use these checks to run code only on the right system.
Examples
This script prints a message depending on whether it runs on Windows or not.
PowerShell
if ($IsWindows) {
    Write-Output "Running on Windows"
} else {
    Write-Output "Not Windows"
}
This uses the platform info from PowerShell to decide what to print.
PowerShell
switch ($PSVersionTable.Platform) {
    'Win32NT' { Write-Output "Windows platform" }
    'Unix' { Write-Output "Unix-like platform" }
    default { Write-Output "Unknown platform" }
}
Sample Program
This script checks the platform and prints a message for Windows, Linux, macOS, or unknown systems.
PowerShell
if ($IsWindows) {
    Write-Output "This script runs on Windows."
} elseif ($IsLinux) {
    Write-Output "This script runs on Linux."
} elseif ($IsMacOS) {
    Write-Output "This script runs on macOS."
} else {
    Write-Output "Unknown platform."
}
OutputSuccess
Important Notes
Always test your script on the platforms you want to support.
File paths use backslashes (\) on Windows and slashes (/) on Linux/macOS.
Some commands or features may not exist on all platforms.
Summary
Use $IsWindows, $IsLinux, and $IsMacOS to detect the platform in PowerShell.
Write platform-specific code inside conditional blocks to avoid errors.
Testing on each platform ensures your script works everywhere.