0

So I am trying to verify if a provided version number is valid or not in powershell with the following code:

$ParsedVersion=''

if ([System.Version]::TryParse("1.2.3.43", [ref]$ParsedVersion)) {
    Write-Host ("valid version")
}
else {
    Write-Host ("invalid version")
}

but I keep getting the error Exception calling "TryParse" with "2" argument(s): "Cannot convert value "" to type "System.Version". Error: "Version string portion was too short or too long.""

I tried lots of different ways but still no luck. I am wondering if there exists a right way to do this? Appreciate your help!

3 Answers 3

1

If you do this instead

$ParsedVersion = $null

it should work..

Sign up to request clarification or add additional context in comments.

Comments

1

This worked for me!

$version = "1.2.3.43"
$IsValid = & {
      try {
        [bool][version]$Version
      } catch [System.Management.Automation.PSInvalidCastException], [System.ArgumentException] {
        # The version is invalid, too long or too short.
        $false
      } catch {
        # definetly not because the version is invalid
        throw $_.Exception
      }
}
if ($IsValid) {
    Write-Host ("valid version")
} else {
    Write-Host ("invalid version")
}

Comments

0

I know this is an old question, but the problem in the original code is that ParsedVersion version is initialized as String and not Version.

$ParsedVersion=[System.Version]::new()

if ([System.Version]::TryParse("1.2.3.43", [ref]$ParsedVersion)) {
    Write-Host ("valid version")
}
else {
    Write-Host ("invalid version")
}

This works as intended.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.