使用powershell用变量替换字符串

时间:2014-11-25 13:13:18

标签: powershell

我正在努力使用下面的代码,这就是我得到的:

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

但是,这就是我想要实现的目标:

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

那么如何强制powershell从HashTable返回所需的值而不是显示:$value

问题是哈希表值中的$。如果我从哈希表中删除它正确显示,但$需要显示在输出中。

代码:

$str = '"FirstName":"f_name","LastName":"l_name","AskCatalog":false,"Nuteres":12","ZipCode":"1234","City":"LA BOUVERIE","Street":"Rue Pasteur","StreetNr":"34","Phone":"12345678","Email":"mail@mail.com"'

$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 个答案:

答案 0 :(得分:2)

不确定我完全理解,但这是一个尝试:

$str = '"FirstName":"f_name","LastName":"l_name","AskCatalog":false,"Nuteres":12","ZipCode":"1234","City":"LA BOUVERIE","Street":"Rue Pasteur","StreetNr":"34","Phone":"12345678","Email":"mail@mail.com"'

$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

我得到的结果是

"FirstName":"${strName}","LastName":"${strSurName}","AskCatalog":false,"Nuteres":12","ZipCode":"${strZipCode}","City":"${strCity}","Street":"${strStreet}","StreetNr":"${strNumber}","Phone":"12345678","Email":"mail@mail.com"