0

I have a powershell script in a file "Publish-MyProj.ps1" with a header defined like this:

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True)]
    [ValidatePattern("\d{1,2}\.\d{1,2}\.\d{1,3}")]
    [string]$Version
)

When I run the script like this:

.\Publish-MyProj.ps1 10.2

It shows an error, which is an expected behaviour.

However, when I run it with an almost alright version:

.\Publish-MyProj.ps1 111.2.25

It does not fail, even though the first number exceeds the number of allowed digits.

Is it a bug or am I doing it wrong?

1 Answer 1

2

It's because you've not specified your regex to match from beginning of the string, so it matches 111.2.25 and doesn't fail.

Use this regex (note ^ modifer): ^\d{1,2}\.\d{1,2}\.\d{1,3}

Or even better: ^\d{1,2}\.\d{1,2}\.\d{1,3}$

P.S. You can easily test your regex at https://regex101.com and see what matches and not.

Example: https://regex101.com/r/aD8xU2/1

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

2 Comments

I am trying to learn powershell, so I have completely missed this rookie mistake while my mind was elsewhere.
@Santhos I think we all had those moments :).

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.