Burre Ifort
Burre Ifort

Reputation: 713

replace strings with variables using powershell

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

Upvotes: 0

Views: 558

Answers (1)

Micky Balladelli
Micky Balladelli

Reputation: 10001

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]"

Upvotes: 2

Related Questions