Replacing strings in a file containing ${Some string in variable} in powershell -
i have text file contains keys of hash table in form of ${key}
. need parse text file , replace ${key}
it's value. below code using
#$config hashtable $document = get-content sample.txt foreach ($conf in $config.keys) { [string]$match = '${' + $conf + '}' $document = $document.replace($match, $($config.$conf)) } }
i have tried below alternatives $match
string
[string]$match = "`${" + $conf + "}"
[string]$match='${' $match+=$conf $match+='}'
i tried hard coding string $match='${backup_folder}'
in cases nothing. have tried -match
see if matches returns false. have confirmed text file contains several patterns of ${key}
format , if copy output of $match
, search in file can find patterns. please point out what's wrong. using powershell v5.0
sample input
$config=@{"backup_dir"="_backup";"staging_dir"="_staging"}
contents of sample.txt
overwrites contents of new installation old installation use / path seperator--> <!-- <rename path="" newname=""/> --> <!-- ${backup_dir} rename-> rename file/directory in new installation
output: ${backup_dir}
should replaced _backup
looks there're couple of typos in hashtable. following complete solution can save script , run, or copy console.
$document = @' overwrites contents of new installation old installation use / path seperator--> <!-- <rename path="" newname=""/> --> <!-- ${backup_folder} rename-> rename file/directory in new installation '@ $config=@{"backup_folder"="_backup";"staging_dir"="_staging"} write-output "`n`ninput`n$document" foreach ($conf in $config.keys) { [string]$match = '${' + $conf + '}' $document = $document.replace($match, $config.$conf) } write-output "`n`noutput`n$document"
Comments
Post a Comment