我进行了此循环以迭代一些我要替换内容的文件。
我要替换的内容是一个字符串,看起来像这样:foo="1"
。
我需要您的帮助的是如何查找字符串(我猜是正则表达式)并使用新值更新文件,例如2
。
$files = Get-ChildItem -Recurse -Filter "*.config"
foreach ($file in $files)
{
Get-Content $file.FullName
}
Read-Host
最佳答案
从问题的示例代码中,我假设您正在尝试更新.NET配置文件(即web.config
或app.config
文件)。
鉴于这些文件实际上是XML文件,您可能需要这样对待它们:
$files = Get-ChildItem -Recurse -Filter "*.config"
foreach ($file in $files)
{
# Create an XmlDocument object from the file
$configXml = [xml](Get-Content $file.FullName)
# Find all the nodes in the document
$xmlNodes = $configXml.SelectNodes('//*')
# Keep track of whether we make changes or not
$changeCount = 0
foreach($node in $xmlNodes)
{
# Check if node has a "foo" attribute
if($node.HasAttribute('foo'))
{
# Set 2 as the value
$node.SetAttribute('foo',2)
$changeCount++
}
}
if($changeCount)
{
# At least one node was updated, save to file
$configXml.Save($file.FullName)
}
}
关于powershell - 在文件中的引号之间替换字符串内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34948449/