如何解决如何验证 Powershell 中的 .txt 文件中是否不存在字符串?
我有 10 个 .txt 文件,所有这些文件都有以 01、02、03、04 等 2 位数字开头的行或记录。
File1.txt
01,333,abc,test2,44,55
02,883,def,test5,33,093
03....and so on.
-
现在,如果 powershell 找到不包含以“01”或“02”开头的记录的文件,那么我想抛出错误或异常。
-
另外,如果有这种文件,那么我不想将那个无效的格式文件复制到输出文件夹中。我只想修改和复制有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"
}
}
或者不使用正则表达式:
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"
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。