【问题标题】:How to verify if a string is not present in a .txt file in Powershell?如何验证Powershell中的.txt文件中是否不存在字符串?
【发布时间】:2021-03-31 14:58:44
【问题描述】:

我有 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. 现在,如果 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
    
        
         

【问题讨论】:

  • "一个不包含以0102 开头的记录的文件" - 所以第一行/记录以02, 开头的文件可以吗?跨度>
  • 您的 .txt 文件听起来像 .CSV 文件...
  • @Mathias,如果 01 和 02 都不存在,那么这将是无效文件的完美案例。
  • @T-Me,这是一个.txt文件。
  • @nick235 但是,如果它的内容遵循csv 的规则,你可以把它当作一个;)

标签: powershell shell automation powershell-4.0 script


【解决方案1】:

这样做的一种方法是

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

【讨论】:

  • @nick235 如果回复对您有帮助,您可以接受它作为答案,这对阅读此主题how_does_accepting_an_answer_work的其他社区成员可能会有所帮助@
  • 嗨 Theo,这很好用,但还有另一个问题。如果文件中的任何一个或多个文件由于某种原因没有被修改,那我们怎么能抛出异常呢?
  • @nick235 如果修改的意思类似于earlier question 中的内容,那么那里的Set-Content 和/或Copy-Item cmdlet 应该抛出终止异常。如果您还想强制抛出非终止异常,请将其包装在 try {..Set-Content..} catch{ trhow } 块中,并将 -ErrorAction Stop 添加到两个 cmdlet。
  • @nick 我已经编辑了我的答案here,向您展示了如何做到这一点。如果您要accept我对这个问题的回答会很好,因为您已经评论过它解决了您的问题。
猜你喜欢
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 2013-10-28
  • 1970-01-01
  • 2017-11-27
  • 2016-01-07
  • 2021-07-09
相关资源
最近更新 更多