2017-07-25 79 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

相關問題