最後3項工作是通過從您的版本定義的變量部分注入值,坦率地說我只是不喜歡期間 - 我更喜歡將應用程序配置作爲代碼(密碼除外)源代碼控制的配置文件。然後我通過PowerShell進行令牌替換,作爲我的應用程序部署腳本的一部分。
這是我編寫並常用來執行令牌替換的函數。如果將它放入PowerShell模塊中,它可以很好地工作,但作爲獨立功能很好。
function Invoke-ReplaceTokens {
param(
[string]$FileSpec,
[string]$FilePath,
[HashTable]$Values)
try {
$files = gci -Path $FilePath -Filter $FileSpec -Recurse
Write-Output "Found files:"
Write-Output ($files | select-object -expandproperty FullName)
$files | % {
$contents = Get-Content $_.FullName -Raw
$changedContents = $false
foreach ($key in $Values.Keys) {
if ($contents.Contains($key)) {
Write-Output "$($_.FullName) contains `"$key`". Replacing it with `"$($Values[$key])`""
$contents = $contents.Replace($key, $Values[$key])
$changedContents = $true
}
}
if ($changedContents) {
set-content -Path $_.FullName -Value $contents
}
}
}
catch {
Write-Output $_
throw $_
}
}
使用的部署腳本:
Invoke-ReplaceTokens -FileSpec '*.config' -FilePath 'C:\Location\Of\My\Config\File' -Values @{ '__Token__' = 'ActualValue' }
而且,這個問題你問這是題外話堆棧溢出(異地資源的建議是題外話),所以我回答您最初的問題的自然演變:「部署期間配置文件管理的好方法是什麼?」
更新 - 我最終在解決方案中包含所有環境特定的配置文件,然後創建另一個「發佈構建工件」任務,將其複製到服務器。然後,我添加了一個PowerShell發佈任務,將特定於環境的文件複製到實際文件中,例如「web.config.pre-production」複製到web.config。 – Mike