F operator - PowerShell


Overview

The -F operator is the Flags operator, used to inspect the ExitStatus property of a cmdlet, script, function, or executable. It’s commonly used in conditionals to determine whether a command or script succeeded or failed.

Syntax

-F {Expression}

Options/Flags

None.

Examples

Determine if a command exited with a non-zero exit code:

if ((Get-Item 'C:\nonexistent\file.txt') -F) {
    Write-Error "File not found."
}

Check if a script exited successfully:

$scriptResult = Invoke-Expression "& 'C:\path\to\script.ps1'"
if (-not $scriptResult -F) {
    Write-Error "Script failed with exit code $($scriptResult.ExitStatus)."
}

Common Issues

Avoid checking the -F operator in unexpected situations, such as assigning it to a variable, as it may result in unexpected or erroneous results.

Integration

The -F operator can be combined with other conditional operators, such as -eq and -ne, for more granular exit code checks.

if ((Get-Service 'Spooler') -F -ne 0) {
    Write-Warning "Spooler service is not running."
}