2017-05-05 23 views
1

我想僅在特定字符串不存在於特定文件中時才運行powershell命令。如果文件不包含字符串powershell

這是我的腳本

$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="C\temp\Software.exe.config" 

[IO.File]::ReadAllText($filename).Replace($pattern,$textToAdd) | Set-Content $filename -Force 

如果$textToAdd字符串不是那麼我想運行此腳本filename $。我如何去做這件事?

回答

1

這很簡單,您只需讀取文本,管道到Where,然後在ForEach塊中執行替換和Set-Content

$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="C\temp\Software.exe.config" 

[IO.File]::ReadAllText($filename)| Where{$_ -notlike "*$texttoadd*"} | ForEach{$_.Replace($pattern,$textToAdd) | Set-Content $filename -Force} 
相關問題