我正在尝试编写一个复杂的查找和替换方法,目的是递归搜索所有配置文件的目录(由用户提供),并根据是否替换配置文件中的一组选择的部分/键。选中一系列复选框。
在下面的场景中,我只想用新值替换数据库密码(因此其他值对于此示例并不重要)。
# collect only the configs that contain the section/key names the application is designed to alter
$configs = GCI -Path "$somePath\*.config" -Recurse | Where-Object {
((Select-String -Pattern "DatabasePassword") -ceq $true) -OR
((Select-String -Pattern "SomeKey02") -ceq $true) -OR
((Select-String -Pattern "SomeKey03") -ceq $true)
}
# if the checkbox for Database Password is checked, get the text after its key
if (DBPassword.Checked) {
foreach ($configFile in $configFiles) {
GC $configFile | Foreach-Object {
if ($config -match "DatabasePassword") {
#I know this next part is sorta right, but I haven't been able to get it to work right
$tmpStr = $configfile | Out-String
$start = tmpStr.IndexOf("=") + 2
$end = $tmpStr.IndexOf('"', $start)
$length = $end - $start
$Pass2Replace = $tmpStr.Substring($start, $length)
}
}
}
}
# This Next Section is Contained Within a ForEach Loop
# I believe I am Close, but This Doesn't Quite Work
# Parse Through All Config Files and Replace Keys Based On the '.Checked' Status of Each Check Box
(GC $configFiles) | ForEach-Object {
if ($DBPassword.Checked) {
ForEach-Object { $_.Replace($Pass2Replace, $newPass.Text) }
if ($checkbox02.Checked) {
ForEach-Object { $_.Replace($Key2Replace02, $newStr02.Text) }
if ($checkBox03.Checked) {
ForEach-Object { $_.Replace($Key2Replace03, $newStr03.Text) }
}
# Save Changes
Set-Content $configFile
所以最终,我预期会发生的事情是用户会检查“更新密码”复选框,在GUI文本框中输入新密码,然后单击“更新”按钮。然后,应用程序将查找配置文件,查找键DatabasePassword
,修改存储的值,并保存更改。以下是本段的简化版本:
在:
DatabasePassword = "SomeEncryptedPassword"
后:
DatabasePassword = "AlteredEncryptedPassword"
主要问题:让PowerShell收集这些密钥的未知存储值并仅替换该值的最佳方法是什么?
子问题01:假设主要问题有答案,是否可以只收集一部分储值并替换?
示例:假设我有一个名为ConnectionString
的密钥,其值为((someRandomValue=AWQagaWGAAE#!)(someSetOfStrings))
;但是,我只想收集值的(someRandomValue=AWQagaWGAAE#!)
部分。我如何只收集这部分并替换它(请记住someRandomValue是未知的)?
答案 0 :(得分:0)
还没有回答,我想发帖一个。我没有完全理解你的问题,但我认为我可以通过 3命令行解决你的基本要求。
根据您的代码段,您似乎已经在Powershell
环境中了,并且使用$somepath
文件在目录*.config
中递归搜索和更新。
因此,请简要回答更新DatabasePassword
的答案:
if ($DBPassword.Checked) {
msr.exe -r -p $somepath -f "\.config$" -it "(DatabasePassword)\s*=\s*\S+" -o "`$1 = $newPass.Text" -R
}
同样更新Key2Replace02
Key2Replace03
。所以你可能只需要3 if
并替换命令行。
您可以预览替换而不使用-R
,使用-K
备份
在我打开的项目https://github.com/qualiu/msr tools
目录中查看 msr.exe 。
您可以添加msr.exe
的一些选项,例如--nd "^(target|bin|\.git|\.svn|obj)$"
,只运行msr.exe
或doc网站,例如:https://qualiu.github.io/msr/usage-by-running/msr-Windows.html
(你会在第一次搜索/阅读文件后快速找到它的晚餐)