0

I am struggling with the code below and this is what I get:

"FirstName":"$value","LastName":"$value"......

But, this is what I would like to achieve:

"FirstName":"${strClientName}","LastName":"${strSurName}" .....

So how can I force powershell to return the desired value from the HashTable instead of displaying this: $value

The problem is the $ in the values of the hashtable. If I remove it from the hashtable it displays correctly, but the $ needs to be displayed in the output.

Code:

$str = '"FirstName":"f_name","LastName":"l_name","AskCatalog":false,"Nuteres":12","ZipCode":"1234","City":"LA BOUVERIE","Street":"Rue Pasteur","StreetNr":"34","Phone":"12345678","Email":"[email protected]"'

$list = @{FirstName="${strName}";
          LastName="${strSurName}";
          ZipCode="${strZipCode}";
          City="${strCity}";
          Street="${strStreet}";
          StreetNr="${strNumber}"}

foreach($item in $list.GetEnumerator())
{
    $key = $item.Key
    $value = $item.Value
    $pattern = '("'+$key+'":)".*?"'
    $changed = "`$1`"`$value`""
    $result = $str = $str -replace $pattern, $changed
}

Write-Host $result

1 Answer 1

2

Not sure I fully understand, but here is a try:

$str = '"FirstName":"f_name","LastName":"l_name","AskCatalog":false,"Nuteres":12","ZipCode":"1234","City":"LA BOUVERIE","Street":"Rue Pasteur","StreetNr":"34","Phone":"12345678","Email":"[email protected]"'

$list = @{FirstName='${strName}';
      LastName='${strSurName}';
      ZipCode='${strZipCode}';
      City='${strCity}';
      Street='${strStreet}';
      StreetNr='${strNumber}'}

foreach($item in $list.GetEnumerator())
{
    $key = $item.Key
    $value = $item.Value
    $pattern = '("'+$key+'":)".*?"'
    $changed = "`$1`"$value`""
    $result = $str = $str -replace ($pattern, $changed)
}

Write-Host $result

Result I get is

"FirstName":"${strName}","LastName":"${strSurName}","AskCatalog":false,"Nuteres":12","ZipCode":"${strZipCode}","City":"${strCity}","Street":"${strStreet}","StreetNr":"${strNumber}","Phone":"12345678","Email":"[email protected]"
Sign up to request clarification or add additional context in comments.

5 Comments

I have tried to remove the ( ` ) character before but it returns empty string. So it does now. How come that you get that result? What did you change in the code?
basically this line: $changed = "$1"$value""`
Oh and also the $list, notice it has single quotes instead of doubles. Anyway try with the complete code. You should see the same results as I do.
I see now. All along it was the single quotes on the list. Thanks, it worked. Very strange because I have been banging my head for 2 or 3 hours trying to figure out why it did not work.
As they say, four eyes see better than two ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.