I want to pass in a comma separated list of values into a script as part of a single switch.
Here is the program.
param(
[string]$foo
)
Write-Host "[$foo]"
Here is the usage example
PS> .\inputTest.ps1 -foo one,two,three
I would expect the output of this program to be [one,two,three]
but instead it is returning [one two three]
. This is a problem because I want to use the commas to deliminate the values.
Why is powershell removing the commas, and what do I need to change in order to preserve them?
Commas are array separators in PowerShell. You should either escape them or encase the parameter in double quotes and then write some logic to split your string that contains commas. E.g. Your cmdlet call should be: Get-Weather "Shrewsbury,MA?
What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.
The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.
An argument is an expression used when calling the method. But for the purpose of differentiating param and args , you can consider the former as defining parameters that can be either passed to the script (or function etc.)
The comma is a special symbol in powershell to denote an array separator.
Just put the arguments in quotes:
inputTest.ps1 -foo "one, two, three"
Alternatively you can 'quote' the comma:
inputTest.ps1 -foo one`,two`,three
Following choices are available
Quotes around all arguments (')
inputTest.ps1 -foo 'one,two,three'
Powershell's escape character before each comma (grave-accent (`))
inputTest.ps1 -foo one`,two`,three
Double quotes around arguments don't change anything !
Single quotes eliminate expanding.
Escape character (grave-accent) eliminates expanding of next character
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With