使用 powershell 替换文本文件中的字符 [英] Replace a char in a text file using powershell
本文介绍了使用 powershell 替换文本文件中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试替换文本文件中的一部分.首先我搜索它是否存在于文本文件中
I'm trying to replace a part on a text file. First i searched if it is present in the text file
$check = Get-Content sample.txt | Where-Object {$_.Contains('<add key="IIS_VERSION" value="7" />')}
if ($checkIISv)
{
Write-Host "IIS's version is already 7"
}
else
{
Write-Host "Update IIS version to 7"
# I want to place here a code that will replace the value="7" if it is not =7
# This value is usually not 7
}
请帮忙,我不认为可以在这里使用替换功能,因为值"被认为是未知的.
Please help, I dont think the replace function can be used here since the "value" is considered as unknown.
推荐答案
您可以使用带有正则表达式模式的 -replace
来替换值.但是,这是一个 web/app xml-config,因此您应该将其修改为 XML 文档.例如
You could use -replace
with a regex-pattern to replace the value. However, this is an web/app xml-config so you should modify it as an XML-document. Ex.
#$xml = [xml](Get-Content "c:\folder\app.config")
$xml = [xml]@"
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="IIS_VERSION" value="8" />
<add key="somekey" value="somevalue" />
</appSettings>
</configuration>
"@
$IISVersion = $xml.SelectSingleNode("//add[@key='IIS_VERSION']")
if ($IISVersion.Value -eq 7)
{
Write-Host "IIS's version is already 7"
}
else
{
Write-Host "Update IIS version to 7"
$IISVersion.Value = "7"
}
$xml.Save("c:\folder\app.config")
这篇关于使用 powershell 替换文本文件中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文