Henno
Henno

Reputation: 245

Parsing custom arguments in Powershell "-" delimitted

I have a string

-car:"Nissan" -Model:"Dina" -Color:"Light-blue" -wheels:"4"

How can I extract the arguments? Initial thoughts was to use the '-' as the delimiter, however that's not going to work.

Upvotes: 0

Views: 832

Answers (1)

Roman Kuzmin
Roman Kuzmin

Reputation: 42035

Use of a regular expression is probably the easiest solution of the task. This can be done in PowerShell:

$text = @'
-car:"Nissan" -Model:"Dina" -Color:"Light-blue" -wheels:"4" -windowSize.Front:"24"
'@

# assume parameter values do not contain ", otherwise this pattern should be changed
$pattern = '-([\.\w]+):"([^"]+)"'

foreach($match in [System.Text.RegularExpressions.Regex]::Matches($text, $pattern)) {
 $param = $match.Groups[1].Value
 $value = $match.Groups[2].Value
 "$param is $value"
}

Output:

car is Nissan
Model is Dina
Color is Light-blue
wheels is 4
windowSize.Front is 24

Upvotes: 1

Related Questions