Skip to content

5.1 Hashtable Expression Parsing #23

Description

@mattcargile

In 5.1, when the key's value is an expression ( maybe only if ), you see red. while kind of breaks with a stream of errors. foreach does work. try {} catch {} does not work. try {} finally {} works.

This is fixed in modern PowerShell ( at least 7.6.1 ).

@{
    Value1 = if ($true) {'SomeValue'}
    Value2 = 'OtherValue'
}

The above throws the below.

At line:2 char:38
+     Value1 = if ($true) {'SomeValue'}
+                                      ~
The hash literal was incomplete.
At line:3 char:5
+     Value2 = 'OtherValue'
+     ~~~~~~
Unexpected token 'Value2' in expression or statement.
At line:5 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : IncompleteHashLiteral

The workaround could be adding a semicolon

@{
    Value1 = if ($true) {'SomeValue'};
    Value2 = 'OtherValue'
}

or wrapping in sub-expression operator

@{
    Value1 = $(if ($true) {'SomeValue'})
    Value2 = 'OtherValue'
}

or you can add an else. ( NOTE: Removing $null in else {} to keep the same semantics. See @surfingoldelephant's comments below.

@{
    Value1 = if ($true) {'SomeValue'} else {}
    Value2 = 'OtherValue'
}

Props to @kborowinski on PowerShell Discord for discovering it. Appears the parser gets "stuck" in the "else/elseif" mode.

Activity

  1. surfingoldelephant commented on May 29, 2026

    @surfingoldelephant

    In case it's of interest, here's the original issue and fix (made in v6.1):

    or you can add an else

    @{
        Value1 = if ($true) {'SomeValue'} else {$null}
        Value2 = 'OtherValue'
    }

    Just watch out for else { $null }. That workaround isn't equivalent to the others.

    When the condition is $false, the other workarounds will result in Value1 being AutomationNull, not $null, due to statement assignment having pipeline semantics.

    For the else workaround to be equivalent, you'd need to do this instead:

    @{
        Value1 = if ($true) { 'SomeValue' } else {}
        Value2 = 'OtherValue'
    }
  2. nightroman commented on Jun 3, 2026

    @nightroman
    Owner

    For sad reasons I am not maintaining this now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions