IF command in Powershell Script

末鹿安然 提交于 2020-01-06 12:43:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!