1

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'?

2
  • 1
    What about ("this, is, a, test" -split ',').trim() Commented Oct 25, 2022 at 7:14
  • 1
    Note that PowerShell already allows you to pass array literals as argument: ./myScript.ps1 -myStringArray this, is, a, 'better test', in which case you don't need to split anything on your own. Commented Oct 25, 2022 at 10:28

1 Answer 1

3

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

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

$myStringArray -split ',\s?' | ForEach-Object {
    Write-Host $_
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! For more flexible whitespace handling you might want to use '\s*,\s*' to remove any number of whitespace chars before and after the comma.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.