如何验证Powershell中的.txt文件中是否不存在字符串



我有10个.txt文件,所有这些文件都有以2位数开头的行或记录,如01、02、03、04。。。等等

File1.txt
01,333,abc,test2,44,55
02,883,def,test5,33,093
03....and so on.
  1. 现在,如果powershell发现一个文件不包含以";01〃;或";02〃;,然后我想抛出一个错误或异常。

  2. 此外,如果有这样的文件,那么我不想将无效格式的文件复制到输出文件夹中。我只想修改和复制有01或02的txt文件。

我该怎么做?

Get-ChildItem -Path 'C:InputFiles'-Filter '*.txt' -File | ForEach-Object { 
$file = $_.FullName
$FileData = Get-Content $file

if($FileData[01] -notlike "01,"){
Write-Host $file "File is INVALID"

}
$data = switch -Regex -File $file {
'^01,' {
do stuff...
}
'^02,' {

do stuff...
}

default {$_}
} 

}
$data | Set-Content -Path $file -Force 
Copy-Item -Path $file -Destination 'C:OutputFiles' -Force



实现这一点的一种方法可能是

Get-ChildItem -Path 'C:InputFiles'-Filter '*.txt' -File | ForEach-Object { 
$isValid = $true
switch -Regex -File $_.FullName {
'^0[12],' { <# line begins with '01' or '02', so it's OK; do nothing #> }
default   { $isValid = $false; break } 
}
if ($isValid) {
# modify the file where you need and copy to the destination folder 
}
else {
Write-Error "File $($_.FullName) is INVALID"
}
}

或者不使用regex:

Get-ChildItem -Path 'C:InputFiles'-Filter '*.txt' -File | ForEach-Object { 
$isValid = $true
foreach ($line in (Get-Content -Path $_.FullName)) {
if ($line -notlike '01,*' -and $line -notlike '02,*') {
$isValid = $false 
break
}
}   
if ($isValid) {
# modify the file where you need and copy to the destination folder 
}
else {
Write-Error "File $($_.FullName) is INVALID"
}
}

最新更新