Powershell查找替换&备用

时间:2014-09-12 13:27:43

标签: powershell replace find backup back

现在,我希望改进我的代码以减少占用空间并提高智能,我需要以下代码才能备份文件,如果它被Find& amp;替换,现在我正在备份所有内容并覆盖旧的备份。

接下来我想要的是不要覆盖备份,而是给它们一个号码,所以如果"备份中有2个相同的备份"文件夹看起来像这样:

  

Filebackup.DCN3 - > Filebackup1.DCN3

所以我总是有原始文件。

get-childitem -path "C:\Users\Administrator\Desktop\Eurocard\SEB" -filter *.* -recurse | copy-item -destination "C:\Users\Administrator\Desktop\Eurocard\Backup" 

(Get-ChildItem "C:\Users\Administrator\Desktop\Eurocard\SEB\*.*" -recurse).FullName |
  Foreach-Object {
   (Get-Content $_ -Raw).
     Replace('*','Æ'). 
     Replace('"','Æ').
     Replace('#','Æ').
     Replace('¤','Æ').
     Replace('&','Æ').
     Replace('(','Æ').
     Replace(')','Æ').
     Replace('=','Æ').
     Replace('?','Æ').
     Replace('´','Æ').
     Replace('`','Æ').
     Replace('|','Æ').
     Replace('@','Æ').
     Replace('£','Æ').
     Replace('$','Æ').
     Replace('{','Æ').
     Replace('[','Æ').
     Replace(']','Æ').
     Replace('}','Æ').
     Replace('^','Æ').
     Replace('~','Æ').
     Replace('¨','Æ').
     Replace('*','Æ').
     Replace('<','Æ').
     Replace('>','Æ').
     Replace('\','Æ').
     Replace('_','Æ').
     Replace(';','Æ').
     Replace('.','Æ').
     Replace('!','Æ')|
   Set-Content $_
  }

有没有人可以帮忙解决这个问题?

1 个答案:

答案 0 :(得分:1)

好吧,要开始你的大部分正则表达式替换可能不起作用,你需要逃避大多数...例如“\”。无论如何,你可以将整个替换缩短为这样的一个表达式:

-replace '[*"#¤&()=?´`|@£${\[\]}^~¨*<>\\_;.!]','Æ'
#query to show it working
'*"#¤&()=?´`|@£${[]}^~¨*<>\_;.!' -replace '[*"#¤&()=?´`|@£${\[\]}^~¨*<>\\_;.!]','Æ'

在此处进行扩展是如何在修改文件时将其仅用于备份:

(Get-ChildItem "C:\Users\Administrator\Desktop\Eurocard\SEB\*.*" -recurse).FullName |
Foreach-Object {
    $Content = (Get-Content $_ -Raw) 
    $Regex = '[*"#¤&()=?´`|@£${\[\]}^~¨*<>\\_;.!]'
    If ($Content | Select-String $Regex -Quiet)
    {
        $Content -Replace $Regex,'Æ'        
        <#
        rest of code block such as copies, backups, renames whatever would go here.
        This way it is only taking place if the file has an unwanted character and is
        modified
        #>        
    }
}