PowerShell查找XML文件指定字符串并移动文件的问题排查
问题分析与解决方案
核心问题出在-match操作符的使用上:-match默认采用正则表达式匹配,而你要查找的字符串[E081]里的[和]是正则的字符类语法——它会匹配E、0、8、1中的任意单个字符,而非字面意义上的[E081],所以导致匹配始终失败,文件全部进入else分支被移到OutputDirectory2。
以下是三种可行的修复方案:
方案1:使用通配符匹配(简单直接)
改用-like操作符,它会把字符串当作字面量处理(仅*和?作为通配符):
$FileDirectory="D:\Test\ImputFileDirectory"; $OutputPath="Z:\Test\OutpuDirectory"; $OutputPath2="Z:\Test\OutputDirectory2"; cls Get-ChildItem $FileDirectory *.xml -recurse -File | ForEach-Object { $FilePath = $_.FullName $Content = Get-Content $FilePath -Raw if ($Content -like '*[E081] Error while archiving*' ) { Move-Item $FilePath $OutputPath } else { Move-Item $FilePath $OutputPath2 } }
方案2:转义正则特殊字符
如果坚持用-match,需要转义正则中的特殊符号([和]),两种方式:
- 手动转义:
if ($Content -match '\[E081\] Error while archiving' )
- 自动转义(适合复杂字符串):
$searchStr = '[E081] Error while archiving' if ($Content -match [regex]::Escape($searchStr) )
方案3:解析XML节点(最严谨)
既然是XML文件,直接定位节点内容更可靠,避免字符串格式差异(如换行、空格)导致的匹配错误:
$FileDirectory="D:\Test\ImputFileDirectory"; $OutputPath="Z:\Test\OutpuDirectory"; $OutputPath2="Z:\Test\OutputDirectory2"; cls Get-ChildItem $FileDirectory *.xml -recurse -File | ForEach-Object { $FilePath = $_.FullName $xml = [xml](Get-Content $FilePath -Raw) $errorText = $xml.dump.errormessage.text.Trim() # 去除可能的首尾空白 if ($errorText -eq '[E081] Error while archiving') { Move-Item $FilePath $OutputPath } else { Move-Item $FilePath $OutputPath2 } }
内容的提问来源于stack exchange,提问作者Jana
相关产品推荐
相关产品推荐

