使用PowerShell在Windows批处理文件中编辑文件



我正在尝试使用批处理脚本编辑配置文件。我环顾四周,我相信Powershell是去这里的方式。我对PowerShell的经验为零,所以我猜该语法是引起我问题的原因。

这是文件现在的样子(本节位于文件的中间(

    <!--add key="MinNumCycles" value="25"/-->
    <!--add key="MaxNumCycles" value="40"/-->

这是我想要的样子

    <!--add key="MinNumCycles" value="25"/-->
    <!--add key="MaxNumCycles" value="40"/-->
    <!--RerunMode: 1 write to DB, 2 write to DB and add to RUN export/-->
    <add key="RerunMode" value="0"/>

这是我在批处理文件中要做的,我需要我的帮助

SET pattern=<!--add key="MaxNumCycles" value="40"/-->
SET textToAdd1=<!--RerunMode: 1 write to DB, 2 write to DB and add to RUN export/-->
SET textToAdd2=<add key="RerunMode" value="0"/>
SET filename=Software.exe.config
powershell -Command "(gc %filename%) -replace "%pattern%", "$&`n`n%textToAdd1%"'n"%textToAdd2%" | sc %filename%"
$pattern='<!--add key="MaxNumCycles" value="40"/-->'
$textToAdd = $pattern + '
    <!--RerunMode: 1 write to DB, 2 write to DB and add to RUN export/-->
    <add key="RerunMode" value="0"/>'
$filename = "Software.exe.config"
([IO.File]::ReadAllText($filename).Replace($pattern,$textToAdd) | Set-Content $filename -Force

这是我个人在所有PowerShell中复制批处理文件的方式。

  1. 您的powershell命令的方式替换会期望正则是正则是您的模式,而您的模式将与您期望的方式不符。它会匹配它,就像它是正则模式一样,并且与您键入的确切字符串不匹配。如果您使用.NET字符串方法.Replace(),则仅查找精确的字符串。
  2. $textToAdd包含完全格式的最终结果,包括我们正在搜索的字符串(开始和最终结果都有字符串,这使我们可以将其保留在那里(以及串联的添加。根据您的描述,字符串标记在日志中间,因此这将允许它进行这些更新并重新添加日志。

来自powershell命令行,这将起作用(假设您的现有内容在conf.bat中(:

$content = Get-Content -Path 'C:pathtoSoftware.exe.config'
$content += "`r`n"
$content += '<!--RerunMode: 1 write to DB, 2 write to DB and add to RUN export/-->'
$content += '<add key="RerunMode" value="0"/>'
Set-Content -Value $content -Path 'C:pathtoSoftware.exe.config'

您可以将其保存为脚本,然后使用:

运行它
powershell.exe -File script.ps1
SET $pattern= '<!--add key="MaxNumCycles" value="40"/-->'
SET $textToAdd1='<!--RerunMode: 1 write to DB, 2 write to DB and add to 
RUN export/-->'
SET $textToAdd2='<add key="RerunMode" value="0"/>'
SET $filename='Software.exe.config'
(Get-Content $filename) -replace pattern, '`n' $textToAdd1 '`n' $textToAdd2 | Set-Content $filename

类似于罗宾的答案,您可以运行另一个脚本。他击败了我:)

最新更新