1

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.

1 Answer 1

2

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  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.