2017-05-02 107 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