Powershell脚本中的IF命令

时间:2014-02-18 15:31:02

标签: powershell if-statement

我已经在下面搜索了一个解决方案,但无法找到任何具体内容。

我有一个Powershell脚本,它检查由人工为任何非法字符手动创建/编辑的XML文件的内容,并用非法字符替换它们。它使用Get -Content和Set -Content命令,如下所示。 然后它将文件从一个位置复制到另一个位置。

(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'

我想修改脚本,以便它只运行Set -Content命令(重新保存文件),如果任何字符已被更改。 无论是否有任何字符被更改,每次运行脚本时仍然需要执行复制命令。

谢谢,

梯子

1 个答案:

答案 0 :(得分:1)

你的意思是

$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'