Home > Software design >  How to include comma in PowerShell function parameter?
How to include comma in PowerShell function parameter?

Time:02-04

I have the following PowerShell function, where I'm validating that the parameter is a number, or a set of numbers separated by commas, or a range of numbers.

function CheckUpkeep() {
    Param(
        [ValidatePattern("\d (,|-\d )*")]
        [Parameter(Mandatory = $true, Position=0)]
        $ID
    )
    Write-Output "ID: $ID" 
}

Example of valid ways to call this are:

CheckUpkeep 1
CheckUpkeep 1-10
CheckUpKeep 1-3,5-10

Output for 1-10 case:
ID: 1-10

Output for 1-3,5-10 case:
ID: 1-3 5-10

How do I update the regex so that the comma is captured as well, without having to use a string quote (whether single or double) when calling the function (CheckUpkeep "1-3,5-10") , such that for the 1-3,5-10 case when I call:

CheckUpkeep 1-3,5-10

the output is:

ID: 1-3,5-10

Thanks!

CodePudding user response:

The problem is not how to include the comma, but how to output it again after your processing.

As you do not want to add quotation marks, I assume that you also do not want to escape the comma with a backtick (`). Without quotation marks or escaping, the comma will tell PowerShell to treat your input as an array. That's the correct behaviour imo, as you can directly process numbers of your set of numbers after that, without parsing your comma separated string by yourself.

To output the comma again, change this line:

Write-Output "ID: $ID"

To this line:

Write-Output "ID: $($ID -join ',')"

This will also work correctly for inputs that do not contain commas.

  •  Tags:  
  • Related