2017-05-02 106 views
0

我正在尝试使用批处理脚本编辑配置文件。我环顾四周,我相信PowerShell是去这里的路。我没有与PowerShell的经验,所以我猜测,语法是什么导致我的问题。使用powershell编辑Windows批处理文件中的文件

这里是什么文件看起来像现在(此部分位于文件的中间)

<!--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"/> 

这里就是我m试图做我的批处理文件,我需要帮助

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%" 

回答

2
$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命令执行替换的方式会期望RegEx和您的模式不符合您的预期。它会匹配它,就好像它是一个RegEx模式,并且与您输入的确切字符串不匹配。如果您使用.NET字符串方法.Replace(),它只会查找确切的字符串。
  2. $textToAdd包含完全格式化的最终结果,包括我们正在搜索的字符串(起始和结果都有字符串,这使我们可以将它保留在那里)以及连接的加法。根据您的描述,字符串标记位于日志的中间,所以这将允许它只进行这些更新并重新保存整个日志。
+0

我得到了“方法调用失败,因为[System.Object []]没有包含名为'Replace'的方法。我只是在为'$ filename'执行'powershell.exe -ExecutionPolicy Bypass -File script.ps1' – user1984300

+0

,你是否在使用你想要更新的文件的完整路径,偶然?你的调用运行脚本是好的,错误正在确认 –

+0

我在我的机器上测试过它,一切正常......您使用的是什么版本的Powershell?您可以运行'$ PSVersionTable'在版本2.0上检查 –

0

从PowerShell命令行,这将工作(assum荷兰国际集团现有的内容是conf.bat):

$content = Get-Content -Path 'C:\path\to\Software.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:\path\to\Software.exe.config' 

你可以这样保存为一个脚本,使用运行它:

powershell.exe -File script.ps1 
+0

'-Path“conf.bat”'应该可以在'Get-Content'和'Set-Content'行中使用'-Path'software.exe.config“,或者更好,文件名称是一个可替换的参数。 –

+0

呼叫良好。添加。 – Robin

+0

这将工作在文件的中间?我应该指定我正在使用的部分不在文件末尾 – user1984300

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' 

(Get-Content $filename) -replace pattern, '`n' $textToAdd1 '`n' $textToAdd2 | Set-Content $filename 

类似罗宾的回答只是一个脚本,你可以跑。他击败了我一拳:)

+0

这仍然不适合我。我正在运行像这样 – user1984300

+0

'powershell -Command“(插入最后一行)”' – user1984300