0

I have searched for a solution on the below but cant find anything specific.

I have a Powershell script which checks the contents of an XML file which has been manually created/edited by a human for any illegal characters and replaces them with non illegal characters. It uses the Get -Content and Set -Content commands as below. It then copies the file from one location to another.

(Get-Content 'C:\SourceLocation\filename.xml') | 
Foreach-Object {$_ -replace "&", "+" `
-replace "£", "GBP" `
-replace "'", "" `
-replace "–", " " `
-replace "’", "" `
-replace "(?<!\?xml.*)(?<=`".*?)`"(?=.*?`")", ""} |
Set-Content 'C:\SourceLocation\filename.xml'
Copy-Item -Path 'C:\SourceLocation\filename.xml' -Destination 'C:\DestinationLocation\filename.xml'

I want to amend the script so that it only runs the Set -Content command (resaves the file) IF any characters have been changed. The copy command still needs to happen each time the script is run regardless of whether any characters have been changed.

Thanks,

Ladders

1 Answer 1

1

Do you mean something like

$b= ($a =Get-Content 'C:\SourceLocation\filename.xml') | 
Foreach-Object {$_ -replace "&", "+" `
-replace "£", "GBP" `
-replace "'", "" `
-replace "–", " " `
-replace "’", "" `
-replace "(?<!\?xml.*)(?<=`".*?)`"(?=.*?`")", ""} 
If (Compare $a $b -PassThru) {
    $b|Set-Content 'C:\SourceLocation\filename.xml'
}
Copy-Item -Path 'C:\SourceLocation\filename.xml' -Destination 'C:\DestinationLocation\filename.xml'
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Adil, that looks like what I'm after yes. I'll give it a whirl and let you know how I get on.
Hi Adil, there just seems to be one small issue - if no replacements are made it seems to open the ps1 file in notepad and keep it open. Can you pehaps add an else statement which closes the script if no replacements are made please?
Umm, open up notepad?? but I do not see anything about notepad in your code.
Don't worry, it's down to the app I am using to run the script when the file changes, not anything to do with the script. Thanks again for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.