Avoid exceptions in Write-ReplaceContentInFile

net8.0
Pat Hartl 2023-11-20 17:34:33 -06:00
parent bc30cc911a
commit 5e3384b4fd
1 changed files with 9 additions and 4 deletions

View File

@ -19,13 +19,18 @@ namespace LANCommander.PowerShell.Cmdlets
public string FilePath { get; set; } public string FilePath { get; set; }
protected override void ProcessRecord() protected override void ProcessRecord()
{
if (File.Exists(FilePath))
{ {
var contents = File.ReadAllText(FilePath); var contents = File.ReadAllText(FilePath);
var regex = new Regex(Pattern, RegexOptions.Multiline); var regex = new Regex(Pattern, RegexOptions.Multiline);
var result = regex.Replace(contents, Substitution); contents = regex.Replace(contents, Substitution);
WriteObject(result); File.WriteAllText(FilePath, contents);
WriteObject(contents);
}
} }
} }
} }