What Is $PSVersionTable?

PowerShell screenshot showing $PSVersionTable output listing keys and values such as PSVersion, PSEdition, OS, Platform, PSCompatibleVersions, BuildVersion, CLRVersion and WSManStack.

What Is $PSVersionTable?

Understanding the Foundation of PowerShell Environment Information

When working with PowerShell, whether you're a system administrator managing enterprise infrastructure or a developer automating deployment pipelines, understanding your execution environment isn't just helpful—it's essential. The version of PowerShell you're running directly impacts which cmdlets are available, what syntax works, and how your scripts will behave across different systems. Without this knowledge, you're essentially navigating in the dark, potentially writing code that works on your machine but fails spectacularly elsewhere.

$PSVersionTable is an automatic variable in PowerShell that contains a read-only hash table displaying detailed information about the PowerShell version and execution environment currently running on your system. This built-in diagnostic tool provides instant access to critical version information, platform details, and compatibility data that helps you write more robust, portable scripts and troubleshoot environment-specific issues effectively.

Throughout this exploration, you'll discover exactly what information $PSVersionTable reveals, how to interpret each property it contains, practical ways to use this data in your daily workflows, and why checking version information should become second nature in your PowerShell practice. We'll examine real-world scenarios where this knowledge prevents problems, explore the differences between Windows PowerShell and PowerShell Core, and provide actionable techniques for leveraging this information in your automation strategies.

Core Components and Properties Revealed

The $PSVersionTable variable exposes several key properties that paint a complete picture of your PowerShell environment. Each property serves a specific purpose and provides insights that become invaluable when troubleshooting compatibility issues or ensuring your scripts run correctly across different systems.

PSVersion: The Primary Version Identifier

The PSVersion property represents the most frequently referenced piece of information—the actual version number of PowerShell itself. This semantic version number follows the standard major.minor.patch format, allowing you to quickly determine if your environment meets the minimum requirements for specific cmdlets or language features. For Windows PowerShell, you'll typically see versions like 5.1, while PowerShell Core and PowerShell 7+ display versions such as 7.3.4 or higher.

"Version checking isn't paranoia—it's the difference between scripts that work everywhere and scripts that only work on your machine."

This version number directly correlates to feature availability. Certain cmdlets, parameters, and language constructs were introduced in specific versions, making this property your first checkpoint when determining script compatibility. When sharing scripts with colleagues or deploying automation across multiple servers, referencing PSVersion ensures you're not using features that don't exist in older environments.

PSEdition: Understanding Your PowerShell Flavor

The PSEdition property distinguishes between "Desktop" (Windows PowerShell) and "Core" (cross-platform PowerShell). This distinction carries significant implications for module compatibility, available cmdlets, and underlying .NET framework dependencies. Desktop edition runs on the full .NET Framework and is Windows-exclusive, while Core edition runs on .NET Core/.NET and supports Windows, Linux, and macOS.

Understanding which edition you're running becomes critical when working with modules that haven't been updated for cross-platform compatibility. Some legacy modules designed for Windows PowerShell may not function correctly in PowerShell Core, while newer modules often target Core exclusively. Checking PSEdition before loading modules or executing platform-specific commands prevents runtime errors and frustrating debugging sessions.

Property Description Example Value Significance
PSVersion PowerShell version number 7.3.4 Determines available features and cmdlets
PSEdition Edition type (Desktop/Core) Core Indicates platform capabilities and module compatibility
GitCommitId Specific build identifier v7.3.4 Precise build tracking for support purposes
OS Operating system description Microsoft Windows 10.0.19045 Platform-specific script logic
Platform Underlying platform architecture Win32NT Low-level platform identification
PSCompatibleVersions Array of compatible versions 1.0, 2.0, 3.0, 4.0, 5.0, 5.1, 7.3.4 Backward compatibility information
PSRemotingProtocolVersion Remoting protocol version 2.3 Remote session compatibility
SerializationVersion Object serialization version 1.1.0.1 Data exchange compatibility
WSManStackVersion WS-Management stack version 3.0 Remote management capabilities

GitCommitId and Build Information

For PowerShell Core and later versions, the GitCommitId property provides the exact commit identifier from the PowerShell GitHub repository that corresponds to your installed build. This granular level of detail proves invaluable when reporting bugs, verifying security patches, or confirming that specific fixes have been applied to your environment. The commit ID allows you to trace back to the exact source code state of your PowerShell installation.

Operating System and Platform Details

The OS and Platform properties deliver operating system information that enables platform-aware scripting. The OS property provides a human-readable description of your operating system, including version numbers, while Platform offers a more technical identifier like "Win32NT" for Windows or "Unix" for Linux and macOS systems.

"Cross-platform scripting isn't about writing the same code everywhere—it's about knowing where you are and adapting accordingly."

These properties become essential when writing scripts that need to behave differently based on the underlying operating system. Perhaps you need to use different path separators, invoke platform-specific commands, or adjust behavior based on filesystem characteristics. Rather than making assumptions, you can query these properties and make informed decisions in your script logic.

Practical Applications in Daily Workflows

Accessing $PSVersionTable information isn't just an academic exercise—it directly impacts how you write, test, and deploy PowerShell solutions. The following scenarios demonstrate real-world applications where this automatic variable becomes indispensable.

Script Compatibility Validation

Before executing any script, especially those obtained from external sources or repositories, validating version compatibility prevents unexpected failures. By checking $PSVersionTable at the beginning of your scripts, you can implement graceful exits with informative error messages rather than cryptic failures deep in execution.

if ($PSVersionTable.PSVersion.Major -lt 7) {
    Write-Error "This script requires PowerShell 7.0 or higher. Current version: $($PSVersionTable.PSVersion)"
    exit 1
}

This proactive approach saves time by immediately alerting users to incompatibilities rather than letting them discover problems through failed commands or unexpected behavior. It transforms error messages from confusing technical jargon into actionable information that guides users toward solutions.

Module Compatibility Checking

When developing or distributing PowerShell modules, checking PSEdition ensures your code runs on the intended platform. Some modules rely on Windows-specific APIs or .NET Framework classes that don't exist in PowerShell Core, while others leverage cross-platform capabilities that aren't available in Windows PowerShell.

"Compatibility checking isn't defensive programming—it's respectful programming that values your users' time."

Incorporating edition checks into module manifests or initialization scripts prevents loading modules in unsupported environments, providing clear feedback about requirements rather than cryptic runtime errors. This practice demonstrates professional module development and respects your users' time by failing fast with helpful information.

Environment Documentation and Troubleshooting

When reporting issues or collaborating with teams, providing complete environment information accelerates troubleshooting. Rather than manually collecting version details, piping $PSVersionTable to various formatting cmdlets generates comprehensive environment reports.

$PSVersionTable | Format-List
$PSVersionTable | ConvertTo-Json | Out-File "environment-info.json"

These commands create documentation that captures your exact environment state, making it easier for others to reproduce issues or verify that fixes apply to your specific configuration. The JSON export option creates machine-readable documentation that can be programmatically analyzed or compared across multiple systems.

Interpreting Version Numbers and Compatibility

Understanding semantic versioning principles helps you interpret $PSVersionTable data effectively and make informed decisions about script compatibility and feature usage.

Major Version Implications

Major version changes (the first number in the version string) typically indicate significant architectural changes, potential breaking changes, or major feature additions. The transition from PowerShell 5.1 to PowerShell 6.0 represented a fundamental shift from Windows-only to cross-platform, while PowerShell 7.0 introduced compatibility improvements and feature convergence.

When your script requires features from a specific major version, checking $PSVersionTable.PSVersion.Major provides a simple compatibility gate. However, remember that major version increments don't always mean newer is better for every scenario—some environments deliberately maintain older versions for stability or compatibility reasons.

Minor and Patch Versions

Minor versions (the second number) typically introduce new features while maintaining backward compatibility, while patch versions (the third number) focus on bug fixes and security updates. Understanding this hierarchy helps you determine whether upgrading is necessary for your specific needs.

"Version requirements should be as permissive as possible and as restrictive as necessary—no more, no less."
Version Component Typical Changes Compatibility Impact Upgrade Decision
Major Architectural changes, breaking changes, major features May break existing scripts Test thoroughly before upgrading
Minor New features, cmdlets, parameters Generally backward compatible Safe to upgrade with minimal testing
Patch Bug fixes, security updates Should not break compatibility Upgrade promptly for security

PSCompatibleVersions Array

The PSCompatibleVersions property contains an array of all PowerShell versions that the current installation maintains compatibility with. This property proves particularly useful when determining if scripts written for older versions will function correctly in your environment.

For example, PowerShell 7.3 lists compatibility with versions 1.0 through 5.1 and itself, indicating that scripts written for those versions should generally work without modification. However, this represents language compatibility rather than module or cmdlet availability—some Windows PowerShell-specific cmdlets may not exist in PowerShell Core despite version compatibility.

Remote Session Considerations

When working with PowerShell remoting, $PSVersionTable takes on additional significance because you're often connecting to systems with different PowerShell versions than your local machine. Understanding how to check remote version information prevents compatibility issues before they cause problems.

Querying Remote Version Information

Before executing complex commands on remote systems, checking their PowerShell version ensures compatibility. You can retrieve remote $PSVersionTable information using Invoke-Command:

Invoke-Command -ComputerName Server01 -ScriptBlock { $PSVersionTable }

This approach allows you to programmatically verify that remote systems meet your script requirements before attempting execution. For scripts that manage multiple servers, collecting version information from all targets helps identify systems that need updates or special handling.

PSRemotingProtocolVersion Significance

The PSRemotingProtocolVersion property indicates the version of the PowerShell remoting protocol in use. This becomes important when establishing remote sessions between systems running different PowerShell versions, as protocol mismatches can cause connection failures or unexpected behavior.

"Remote execution without version verification is like shipping code to production without testing—technically possible, but professionally inadvisable."

Modern PowerShell versions maintain backward compatibility with older remoting protocols, but certain advanced features may only be available when both endpoints support the same protocol version. Checking this property helps diagnose connection issues and determine if protocol limitations are constraining your remote management capabilities.

Leveraging Version Information in Scripts

Beyond simple compatibility checks, $PSVersionTable enables sophisticated script logic that adapts to different environments automatically. This adaptive approach creates more robust, portable scripts that work across diverse infrastructure.

Conditional Feature Usage

Rather than requiring specific versions, well-designed scripts detect available features and adapt accordingly. This approach maximizes compatibility while leveraging newer capabilities when available:

if ($PSVersionTable.PSVersion.Major -ge 7) {
    # Use PowerShell 7+ features
    $data = Get-Content "data.json" | ConvertFrom-Json -AsHashtable
} else {
    # Fallback for older versions
    $data = Get-Content "data.json" | ConvertFrom-Json
}

This pattern allows scripts to function across version boundaries while taking advantage of improvements in newer releases. Users on older systems get working functionality, while those on current versions benefit from enhanced performance or features.

Platform-Specific Code Paths

Cross-platform scripts often need different implementations for Windows versus Linux/macOS. Using $PSVersionTable.Platform or $PSVersionTable.OS enables clean platform detection:

$isWindows = $PSVersionTable.Platform -eq 'Win32NT' -or $PSVersionTable.PSEdition -eq 'Desktop'

if ($isWindows) {
    $configPath = "$env:APPDATA\MyApp\config.json"
} else {
    $configPath = "$HOME/.config/myapp/config.json"
}

This approach creates maintainable code that clearly communicates platform-specific logic rather than relying on error handling or assumptions about environment characteristics.

Automated Environment Reporting

For organizations managing numerous systems, collecting $PSVersionTable information across infrastructure provides valuable inventory data. Combined with configuration management tools or scheduled tasks, this creates an automated inventory of PowerShell versions and capabilities:

$report = [PSCustomObject]@{
    ComputerName = $env:COMPUTERNAME
    PSVersion = $PSVersionTable.PSVersion.ToString()
    PSEdition = $PSVersionTable.PSEdition
    OS = $PSVersionTable.OS
    Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}

$report | Export-Csv -Path "\\server\share\ps-inventory.csv" -Append -NoTypeInformation

This automated inventory helps identify systems requiring updates, track PowerShell adoption across your environment, and plan migration strategies when moving between PowerShell versions or editions.

Common Pitfalls and Misconceptions

Despite its straightforward nature, several common misunderstandings about $PSVersionTable can lead to problems in script development and deployment.

Assuming Version Equals Capability

A common mistake involves assuming that a specific PowerShell version guarantees the availability of particular cmdlets or modules. While core PowerShell cmdlets correspond to version numbers, many cmdlets come from separate modules that may or may not be installed regardless of PowerShell version.

For example, Active Directory cmdlets aren't part of PowerShell itself—they're provided by the ActiveDirectory module that must be separately installed. Checking $PSVersionTable.PSVersion tells you nothing about module availability. Always verify module presence using Get-Module -ListAvailable rather than assuming version implies capability.

Ignoring Edition Differences

Some developers check PSVersion but ignore PSEdition, leading to scripts that work in Windows PowerShell but fail in PowerShell Core or vice versa. These editions have different underlying frameworks and available cmdlets, making edition checking just as important as version checking for compatibility validation.

"The most elegant compatibility check is the one that prevents the problem before it manifests as a cryptic error message."

Hardcoding Version Requirements

Requiring exact version matches rather than minimum versions creates unnecessary restrictions. Unless you're working around a specific bug in a particular version, checking for minimum requirements provides better compatibility:

# Too restrictive
if ($PSVersionTable.PSVersion.ToString() -ne "7.3.4") {
    throw "Requires exactly PowerShell 7.3.4"
}

# Better approach
if ($PSVersionTable.PSVersion.Major -lt 7) {
    throw "Requires PowerShell 7.0 or higher"
}

The second approach allows your script to work with current and future versions while still enforcing meaningful requirements. This future-proofs your code and reduces maintenance burden as new PowerShell versions release.

Advanced Techniques and Patterns

Beyond basic version checking, sophisticated PowerShell developers leverage $PSVersionTable in advanced patterns that create more resilient, maintainable automation solutions.

Version-Aware Module Design

When developing modules intended for distribution, incorporating version checks into module manifests and initialization scripts ensures compatibility before functions load. The module manifest's PowerShellVersion and CompatiblePSEditions fields provide declarative version requirements, while initialization scripts can perform runtime validation:

# In module manifest (.psd1)
@{
    PowerShellVersion = '5.1'
    CompatiblePSEditions = @('Desktop', 'Core')
}

# In module initialization (.psm1)
if ($PSVersionTable.PSVersion.Major -lt 5) {
    throw "This module requires PowerShell 5.0 or higher"
}

This dual-layer approach provides both declarative requirements that PowerShell enforces automatically and runtime validation that can deliver custom error messages or perform conditional initialization.

Feature Detection Over Version Detection

Rather than checking versions, advanced scripts detect specific capabilities directly. This approach proves more robust as it tests for actual functionality rather than assuming version implies capability:

# Instead of version checking
if (Get-Command -Name Get-FileHash -ErrorAction SilentlyContinue) {
    $hash = Get-FileHash -Path $file -Algorithm SHA256
} else {
    # Fallback implementation
    $hash = [System.Security.Cryptography.SHA256]::Create().ComputeHash([System.IO.File]::ReadAllBytes($file))
}

This pattern makes code more resilient to environment variations and focuses on actual capabilities rather than proxy indicators like version numbers.

Telemetry and Analytics Integration

Organizations with mature DevOps practices often integrate $PSVersionTable data into telemetry systems, providing insights into PowerShell usage patterns, version distribution, and upgrade progress. This data-driven approach informs infrastructure planning and identifies systems requiring attention:

$telemetry = @{
    EventType = "ScriptExecution"
    ScriptName = $MyInvocation.MyCommand.Name
    PSVersion = $PSVersionTable.PSVersion.ToString()
    PSEdition = $PSVersionTable.PSEdition
    OS = $PSVersionTable.OS
    User = $env:USERNAME
    Timestamp = (Get-Date).ToUniversalTime().ToString("o")
}

# Send to telemetry endpoint
Invoke-RestMethod -Uri "https://telemetry.company.com/api/events" -Method Post -Body ($telemetry | ConvertTo-Json) -ContentType "application/json"

This integration transforms $PSVersionTable from a simple diagnostic tool into a component of enterprise observability infrastructure, providing visibility into PowerShell usage across your organization.

Security and Compliance Considerations

From a security perspective, maintaining current PowerShell versions addresses known vulnerabilities and ensures access to security improvements. Organizations with compliance requirements often need to demonstrate that systems run supported software versions, making $PSVersionTable data valuable for compliance reporting.

Identifying Unsupported Versions

Microsoft's support lifecycle for PowerShell versions means that older versions no longer receive security updates. Scripts that collect and report $PSVersionTable data across infrastructure help identify systems running unsupported versions that represent security risks:

$supportedVersions = @("7.2", "7.3", "7.4")
$currentVersion = $PSVersionTable.PSVersion.ToString()

if ($currentVersion -notin $supportedVersions) {
    Write-Warning "PowerShell version $currentVersion is not in the supported list. Consider upgrading."
}

Regular audits using this approach help maintain security posture by highlighting systems requiring updates before they become compliance violations or security incidents.

Audit Trail and Change Tracking

Including $PSVersionTable information in script logs creates an audit trail that documents the execution environment for each script run. This proves invaluable when investigating incidents or demonstrating compliance with change management processes:

$logEntry = @{
    Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Script = $MyInvocation.MyCommand.Path
    User = $env:USERNAME
    Computer = $env:COMPUTERNAME
    PSVersion = $PSVersionTable.PSVersion.ToString()
    PSEdition = $PSVersionTable.PSEdition
}

$logEntry | ConvertTo-Json | Add-Content -Path "C:\Logs\script-audit.log"

This logging pattern creates comprehensive audit trails that satisfy compliance requirements while providing debugging information when troubleshooting issues.

Testing Strategies Across Versions

Professional PowerShell development includes testing scripts across multiple PowerShell versions to ensure broad compatibility. Understanding $PSVersionTable enables effective testing strategies that catch version-specific issues before deployment.

Multi-Version Test Environments

Setting up test environments with different PowerShell versions allows validation of compatibility claims. Containers and virtual machines make this practical even for individual developers:

# Docker example for testing in PowerShell 7.2
docker run -it --rm -v ${PWD}:/scripts mcr.microsoft.com/powershell:7.2-ubuntu-22.04 pwsh -File /scripts/test-script.ps1

# Docker example for testing in PowerShell 7.3
docker run -it --rm -v ${PWD}:/scripts mcr.microsoft.com/powershell:7.3-ubuntu-22.04 pwsh -File /scripts/test-script.ps1

This containerized testing approach provides consistent, reproducible test environments that validate script behavior across versions without requiring dedicated test infrastructure.

Automated Compatibility Testing

Integrating version checks into automated test suites ensures that compatibility requirements remain enforced as scripts evolve. Pester, PowerShell's testing framework, provides excellent support for version-aware testing:

Describe "Version Compatibility" {
    It "Should require PowerShell 7.0 or higher" {
        $PSVersionTable.PSVersion.Major | Should -BeGreaterOrEqual 7
    }
    
    It "Should support Core edition" {
        $PSVersionTable.PSEdition | Should -Be "Core"
    }
}

These automated checks prevent accidental introduction of version-specific code that breaks compatibility promises, maintaining script reliability across your supported version range.

Future-Proofing Your Scripts

PowerShell continues evolving, with new versions introducing features and occasionally deprecating old patterns. Writing scripts that gracefully handle version differences ensures longevity and reduces maintenance burden.

Defensive Version Checking

Rather than assuming the current version is the maximum, write checks that work regardless of future versions:

# Avoid
if ($PSVersionTable.PSVersion.Major -eq 7) {
    # This breaks when PowerShell 8 releases
}

# Prefer
if ($PSVersionTable.PSVersion.Major -ge 7) {
    # This continues working in future versions
}

This forward-looking approach prevents scripts from breaking when new PowerShell versions release, reducing technical debt and maintenance requirements.

Embracing Progressive Enhancement

Design scripts that work with minimum requirements but leverage newer features when available. This progressive enhancement strategy maximizes compatibility while rewarding users who maintain current versions:

function Get-ProcessInfo {
    param([string]$ProcessName)
    
    $process = Get-Process -Name $ProcessName
    
    # Basic information works everywhere
    $info = [PSCustomObject]@{
        Name = $process.Name
        ID = $process.Id
        CPU = $process.CPU
    }
    
    # Enhanced information for PowerShell 7+
    if ($PSVersionTable.PSVersion.Major -ge 7) {
        $info | Add-Member -NotePropertyName Company -NotePropertyValue $process.Company
        $info | Add-Member -NotePropertyName Description -NotePropertyValue $process.Description
    }
    
    return $info
}

This pattern delivers value to all users while providing enhanced functionality to those on current versions, creating incentive for upgrades without forcing them.

Documentation and Communication

Clear documentation of version requirements prevents confusion and sets appropriate expectations for script users. Always document PowerShell version dependencies prominently in README files, script comments, and module manifests.

Effective Requirement Communication

When documenting version requirements, specify not just the minimum version but also any edition requirements and the reason for the requirement:

<#
.SYNOPSIS
    Automates server configuration deployment

.DESCRIPTION
    This script automates the deployment of server configurations using
    modern PowerShell features for improved performance and reliability.

.NOTES
    Requirements:
    - PowerShell 7.2 or higher (required for specific parameter features)
    - PowerShell Core edition (required for cross-platform compatibility)
    - Tested on Windows, Linux, and macOS
    
    Version History:
    - 1.0.0: Initial release (requires PS 5.1+)
    - 2.0.0: Updated for cross-platform support (requires PS 7.0+)
    - 2.1.0: Added enhanced error handling (requires PS 7.2+)
#>

This documentation style provides context for requirements rather than arbitrary restrictions, helping users understand why specific versions are necessary and what benefits they provide.

Runtime Requirement Validation

Combine documentation with runtime validation to catch compatibility issues immediately:

$requiredVersion = [Version]"7.2"
$currentVersion = $PSVersionTable.PSVersion

if ($currentVersion -lt $requiredVersion) {
    $message = @"
This script requires PowerShell $requiredVersion or higher.
Current version: $currentVersion
PowerShell Edition: $($PSVersionTable.PSEdition)

Please upgrade to PowerShell $requiredVersion or higher:
https://github.com/PowerShell/PowerShell/releases
"@
    throw $message
}

This approach transforms version mismatches from cryptic errors into helpful messages that guide users toward resolution, improving user experience and reducing support burden.

Performance and Efficiency Considerations

While accessing $PSVersionTable is lightweight, understanding performance implications helps optimize script execution, particularly in scenarios where version checks occur frequently.

Caching Version Information

For scripts that check version information repeatedly, caching $PSVersionTable data in script-scope variables improves efficiency:

$script:PSVersion = $PSVersionTable.PSVersion.Major
$script:IsCore = $PSVersionTable.PSEdition -eq "Core"

function Test-Feature {
    if ($script:PSVersion -ge 7 -and $script:IsCore) {
        # Use version-specific feature
    }
}

This pattern eliminates redundant hash table lookups while maintaining clear, readable code that communicates version dependencies.

Lazy Evaluation Patterns

For expensive version-dependent operations, implement lazy evaluation that only checks versions when necessary:

$script:AdvancedFeatureAvailable = $null

function Use-AdvancedFeature {
    if ($null -eq $script:AdvancedFeatureAvailable) {
        $script:AdvancedFeatureAvailable = $PSVersionTable.PSVersion.Major -ge 7 -and 
                                           (Get-Command -Name New-AdvancedCmdlet -ErrorAction SilentlyContinue)
    }
    
    if ($script:AdvancedFeatureAvailable) {
        # Use advanced feature
    } else {
        # Use fallback implementation
    }
}

This approach combines version checking with feature detection, performing the check once and caching the result for subsequent calls.

Integration with Configuration Management

Modern infrastructure often involves configuration management tools like Ansible, Chef, or Puppet. Integrating $PSVersionTable data with these systems creates comprehensive infrastructure visibility and enables policy enforcement.

Ansible Integration Example

Ansible playbooks can collect PowerShell version information as facts, enabling conditional task execution based on PowerShell capabilities:

- name: Gather PowerShell version information
  win_shell: |
    $PSVersionTable | ConvertTo-Json
  register: ps_version_raw

- name: Parse PowerShell version
  set_fact:
    ps_version: "{{ ps_version_raw.stdout | from_json }}"

- name: Execute PowerShell 7+ specific tasks
  win_shell: |
    # PowerShell 7+ specific commands
  when: ps_version.PSVersion.Major | int >= 7

This integration enables infrastructure-as-code practices that respect PowerShell version differences across managed systems.

Policy-Based Version Management

Organizations can implement policies requiring minimum PowerShell versions for specific server roles or security classifications. Scripts that check and enforce these policies help maintain compliance:

$requiredVersions = @{
    "WebServer" = [Version]"7.2"
    "DatabaseServer" = [Version]"7.3"
    "DomainController" = [Version]"5.1"
}

$serverRole = (Get-ItemProperty "HKLM:\SOFTWARE\Company\ServerRole").Role
$requiredVersion = $requiredVersions[$serverRole]

if ($PSVersionTable.PSVersion -lt $requiredVersion) {
    throw "This $serverRole requires PowerShell $requiredVersion or higher"
}

This policy-driven approach ensures that infrastructure maintains appropriate PowerShell versions based on role-specific requirements.

What is the difference between PSVersion and PSEdition?

PSVersion indicates the specific version number of PowerShell (like 5.1 or 7.3.4), while PSEdition identifies whether you're running "Desktop" (Windows PowerShell) or "Core" (cross-platform PowerShell). Version tells you which features are available, while edition tells you which underlying framework and platform support you have.

How do I check if my script will work on a remote computer with a different PowerShell version?

Use Invoke-Command -ComputerName RemotePC -ScriptBlock { $PSVersionTable } to retrieve version information from the remote system before executing your script. Compare the returned version against your script's requirements to determine compatibility.

Can I modify the values in $PSVersionTable?

No, $PSVersionTable is a read-only automatic variable. Attempting to modify its properties will result in an error. This read-only nature ensures that version information remains accurate and trustworthy for compatibility checking.

Why does my PowerShell 7 show compatibility with version 1.0 when they're completely different?

The PSCompatibleVersions property indicates language-level compatibility, meaning that basic PowerShell syntax and core cmdlets from older versions should work. However, this doesn't guarantee that all modules, cmdlets, or platform-specific features from older versions are available.

What should I do if $PSVersionTable shows an unsupported PowerShell version?

Download and install the latest PowerShell version from the official GitHub repository at https://github.com/PowerShell/PowerShell/releases. For Windows systems, PowerShell 7+ can be installed alongside Windows PowerShell 5.1 without conflicts, allowing you to use both as needed.

How can I ensure my module works across different PowerShell versions?

Implement version checking in your module initialization, specify PowerShellVersion and CompatiblePSEditions in your module manifest, and test your module in containers or virtual machines running different PowerShell versions. Use conditional logic to provide fallback implementations for version-specific features.

SPONSORED

Sponsor message — This article is made possible by Dargslan.com, a publisher of practical, no-fluff IT & developer workbooks.

Why Dargslan.com?

If you prefer doing over endless theory, Dargslan’s titles are built for you. Every workbook focuses on skills you can apply the same day—server hardening, Linux one-liners, PowerShell for admins, Python automation, cloud basics, and more.