Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key value from string using Powershell

I am trying to get key value using Regex in powershell.

$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name

I want output like this :

$key1 = "value1"
$key2 = "value2"
$key3 = "value3"

Output i am getting :

Name : :value1,key2:value2,
like image 602
rAJ Avatar asked May 30 '19 10:05

rAJ


People also ask

How do I use substring in PowerShell?

To find a string inside of a string with PowerShell, you can use the Substring() method. This method is found on every string object in PowerShell. The first argument to pass to the Substring() method is the position of the leftmost character. In this case, the leftmost character is T .

What is @{} in PowerShell?

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'

How do I convert a string to an array in PowerShell?

Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.


Video Answer


2 Answers

If you are using the comma to separate the key:value pairs this should accomplish what you are after.

$string = "key1:value1,key2:value2,key3:value3"
$ht = @{} # declare empty hashtable
$string -split ',' | % { $s = $_ -split ':'; $ht += @{$s[0] =  $s[1]}} 
# split the string by ',', then split each new string on ':' and map them to the hashtable

Outputs the following (note by default they are not ordered)

PS C:\> $ht

Name                           Value
----                           -----
key3                           value3
key1                           value1
key2                           value2
like image 94
sysg0blin Avatar answered Oct 14 '22 03:10

sysg0blin


Pretty sure that sysg0blin's helpful answer can do the job, but if you really want to set specific variables this can be done with such script:

$string = "key1:value1,key2:value2,key3:value3"
$splitted = $string -split ','
$splitted | ForEach-Object {
  $i = $_ -split ":"
  Set-Variable -Name $i[0] -Value $i[1]
}

What you do here is to split string into array of key:value pair and then split each pair into array with 2 elements, first being variable name and second being value of the variable.

like image 33
Robert Dyjas Avatar answered Oct 14 '22 04:10

Robert Dyjas