Home > Net >  Convert comma seperated string from ARG into array in PowerShell
Convert comma seperated string from ARG into array in PowerShell

Time:10-26

Is it possible to take an arg like "this, is, a, test" and create an array in powershell?

Something like

./myScript.ps1 -myStringArray 'this, is, a, test'

And in the code something like:

param (
    [string[]] $myStringArray = @()
)

foreach($item in $myStringArray) {
    Write-Host $item
}

I have tried a few way but they aren't very clean and either create a sentence with or without the commas but no new line per item.

How difficult would it be to support both: 'this, is, a, test' And 'this,is,a,test'?

CodePudding user response:

You could use the -split operator with a simple regex to archive that:

param (
    [string[]] $myStringArray = @()
)

$myStringArray -split ',\s?' | ForEach-Object {
    Write-Host $_
}
  • Related