简体   繁体   English

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

[英]How to verify if a string is not present in a .txt file in Powershell?

I have 10.txt files and all these files have rows or records that start with 2-digit numbers like 01, 02, 03, 04... and so on.我有 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.
  1. Now, if powershell finds a file that doesn't contain a record that starts with either "01" or "02", then i want to throw an error or exception.现在,如果 powershell 找到一个不包含以“01”或“02”开头的记录的文件,那么我想抛出错误或异常。

  2. Also, if there is such kind of file, then i don't want to copy that invalid format file to the output folder.另外,如果有这种文件,那么我不想将该无效格式文件复制到 output 文件夹中。 I only want to modify and copy txt files that have 01 or 02.我只想修改和复制有01或02的txt文件。

How can i do this?我怎样才能做到这一点?

    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
    
        
         

One way of doing this could be这样做的一种方法可能是

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

or do it without using 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"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM