Powershell查找替换和备份

金属迈克

现在,我希望改进我的代码以使用更少的空间并变得更智能,如果通过“查找与替换”对其进行了修改,则我需要下面的代码仅备份文件,现在我正在备份所有内容并覆盖旧的文件。备份。

我想做的下一件事是不覆盖备份,而是给它们一个数字,因此,如果“ backup”文件夹中有两个相同的备份,它将看起来像这样:

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 $_
  }

有谁可以帮助您吗?

诺亚·斯帕克斯(Noah Sparks)

好吧,要开始大部分正则表达式替换可能无法正常工作,您需要转义其中大部分...例如“ \”。无论如何,您可以将整个替换缩短为一个表达式,如下所示:

-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
        #>        
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章