Reputation: 345
In a powershell script, I have a command in the form of a string. I would like to know if there an easy way to extract the arguments in the form of a hashmap.
Input :
$str = "SampleCommandName -Arg1 Value1 -Arg2 Value2"
$command, $parameters = Some-Function $str
Write-Host $parameters[Arg1]
Output : Value1
I tried using ConvertFrom-StringData, but my version of PowerShell does not support Delimiter parameter.
Upvotes: 1
Views: 1897
Reputation: 61068
You could convert that to a hash manually:
$str = "SampleCommandName -Arg1 Value1 -Arg2 Value2"
$hash = [ordered]@{}
$str.Split("-").Trim() | Where-Object { $_.Contains(" ") } | ForEach-Object {
$name, $value = $_ -split '\s+', 2
$hash[$name] = $value
}
$hash
Or you can use ConvertFrom-StringData
and a regex replace to change the space between the name and value into a =
character.
You need to make sure that it only replaces the first occurrence, in order not to interfere with any spaces in the values.
$str = "SampleCommandName -Arg1 Value1 -Arg2 Value2"
($str.Split("-").Trim() | Where-Object { $_.Contains(" ") }) -replace '([^\s]+)\s(.*)', '$1=$2' -join "`r`n" | ConvertFrom-StringData
Alternative without regex:
$str = "SampleCommandName -Arg1 Value1 -Arg2 Value2"
($str.Split("-").Trim() | Where-Object { $_.Contains(" ") } | ForEach-Object { $_.Split(' ', 2) -join '=' }) -join "`r`n" | ConvertFrom-StringData
Output:
Name Value ---- ----- Arg1 Value1 Arg2 Value2
Upvotes: 2