Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assignment of version-like value (numbers with two or more dots) in Powershell

Recently I discover some nasty behavior about assigning some version-like value to variable in Powershell (at least in 7.2.5).

At first I tried:

> $version = 1.2.3
> echo $version

I quickly find out that I have to escape value with quotes to make it string explicitly. This one works well:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> $version = "1.2.3"
> echo $version
1.2.3

The question is: why it works this way? Why pwsh does not throw some kind of error in first example and just converts it to $null? Like in other cases:

> 12a
12a: The term '12a' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

> [int]12a
ParserError:
Line |
   1 |  [int]12a
     |       ~~~
     | Unexpected token '12a' in expression or statement.

So I believe literals like 1.2.3 are expected and managed by some rule.
I tried to dig into documentation about expressions and assignments, but can’t find the correct answer.

>Solution :

why it works this way?

In effect, 1.2.3 is parsed as (1.2).3, i.e. as number literal 1.2 whose .3 property is retrieved.

Number literal 1.2 is an instance of a [double] (double-precision floating point value), and as such has no .3 property (or any other property).

By default, PowerShell quietly returns $null when you try to access a non-existent property on an object.

As Santiago Squarzon points out, you can turn such attempts into (statement-terminating) errors if you use Set-StrictMode -Version 2 or higher:

PS> Set-StrictMode -Version 2; 1.2.3
... The property '3' cannot be found on this object. ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading