问题
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:
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'
来源:https://stackoverflow.com/questions/21858229/if-command-in-powershell-script