1

I cannot convert a properly formatted string stored in a variable into a version type. The issue must be with the variable as it works fine if I provide the value manually but I don't know what could be wrong with it. I am new to PowerShell so I'm not sure where to look.

Here's my variable:

Write-Host "$env:BUILD_BUILDNUMBER"
1.0.0.20​

Is it really a string? Yes:

($env:BUILD_BUILDNUMBER).GetType().fullname
System.String

Let's convert it into a version:

[version]($env:BUILD_BUILDNUMBER)
Cannot convert value "1.0.0.20​" to type "System.Version". Error: "Input string was not in a correct format."

Works just fine when tried manually:

[version]("1.0.0.20")

Any idea what's wrong with my variable? I can't change it as it's provided to me as is.

Thanks!

Bluonic
  • 11
  • 1
  • 2
  • 1
    take a very very very careful look at your string ... i suspect that it has something that is not a digit or a dot in it. possibly a trailing space? feed it to `Format-Hex` so you can see what it actually contains. – Lee_Dailey May 19 '20 at 22:40
  • Good point, @Lee_Dailey, but note that surrounding whitespace isn't the issue (it is ignored). [This answer](https://stackoverflow.com/a/45356836/45375) contains a function that visualizes non-printable characters in a friendlier fashion. – mklement0 May 19 '20 at 22:45
  • Great advice! Thanks! Found this non-printable gibberish at the end: 1.0.0.20​ – Bluonic May 19 '20 at 23:12
  • Good find. I was just about to post you inspect it with: `0..($env:BUILD_BUILDNUMBER.Length-1) | % {[byte][char]($env:BUILD_BUILDNUMBER[$_])} ` – Kory Gill May 19 '20 at 23:13
  • @Bluonic - neato! glad to know that you found the glitch ... [*grin*] – Lee_Dailey May 19 '20 at 23:56
  • @mklement0 - ah! i didn't know that the `[version]` stuff would toss out trailing spaces. good to know. that function is handy ... but seems like overkill for this kind of glitch. i should have suggested what `Kory Gill` suggested as a somewhat more direct method - the `.Length` info is a neat & quick sanity check. – Lee_Dailey May 19 '20 at 23:59
  • 1
    Or replace all characters that are not a dot or a digit like `[version]($env:BUILD_BUILDNUMBER -replace '[^\d.]')` – Theo May 20 '20 at 15:16
  • I ended up cleaning up the variable with: `[version]($env:BUILD_BUILDNUMBER -replace "[^ -~]")` which removes all non printable characters. Thanks everyone!! – Bluonic May 20 '20 at 17:25
  • Glad to hear it, Bluonic. I encourage you to post your solution as an answer, to benefit future readers; however, I recommend using @Theo's approach for robustness. – mklement0 May 21 '20 at 10:47

1 Answers1

1

I also had the same issue, but within my Azure DevOps pipeline (PowerShell task).

I solved this by placing extra brackets around [Version]$someVariable, so it would like: ([Version]$someVariable)