2017-07-25 82 views
1

我有文本文件,其中包含${key}形式的哈希表中的某些键。我需要解析文本文件并用其值替换${key}。下面是我使用

#$config is the hashtable 
    $document = Get-Content sample.txt 
    foreach ($conf in $config.Keys) { 
     [string]$match = '${' + $conf + '}' 
     $document = $document.Replace($match, $($config.$conf)) 
     } 
    } 

我曾尝试下面的替代品$match

[string]$match = "`${" + $conf + "}"

[string]$match='${' 
$match+=$conf 
$match+='}' 

我甚至尝试硬编码字符串作为$match='${BACKUP_FOLDER}'的代码,但在所有的情况下,它确实没有。我也尝试过-match来查看是否匹配,但总是返回false。 我已确认文本文件包含${key}格式的几种模式,如果我复制$match的输出并在文件中搜索,我可以找到模式。你能指出什么是错的。我使用Powershell V5.0

样品输入

[email protected]{"BACKUP_DIR"="_Backup";"STAGING_DIR"="_Staging"} 

sample.txt的内容

Overwrites the contents of new installation with old installation 
    Always use/as path seperator--> 
    <!-- <rename path="" newName=""/> --> 
    <!-- 
    ${BACKUP_DIR} 
    rename-> rename file/directory in new installation 

输出:${BACKUP_DIR}应该_Backup

+0

请编辑问题并添加样本输入和所需的输出数据。 – vonPryz

回答

1

更换看起来有是一对错别字在散列表中。以下是您可以保存为脚本并运行,或复制到控制台的完整解决方案。

$document = @' 
Overwrites the contents of new installation with old installation 
    Always use/as path seperator--> 
    <!-- <rename path="" newName=""/> --> 
    <!-- 
    ${BACKUP_FOLDER} 
    rename-> rename file/directory in new installation 
'@ 

[email protected]{"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" 
+0

谢谢@ gms0ulman。 Typo就在这个问题上。当我将它作为独立脚本运行时,您的脚本能够正常工作,但是当我将它合并到主脚本中时,它不起作用。看起来问题是别的。更多的头部抓挠要完成:( – Pramod

+0

@PramodAhanya确认;你是否注意到'.Replace','$ config。$ conf'中的不同的第二个参数? – gms0ulman

+0

对不起,我正在使用'$ config。 $ conf' – Pramod

相关问题