powershellif-statementsubstring

powershell activity if static string is on substring on file


i need to do an activity when are present a static string on file

if  ( Get-Content -Path C:\appoggio\*.TXT  -filter {$_.Substring(250,5)} ) = '05032' {
 Set-Location C:\appoggio\prova  -WhatIf
 Write-Warning 'ok'
}

the file

           2401188832220240801083447050320240100750910000101002076        IT0000007994            251630830000   00000002401001652820240801   00000000000000000000000000000000000000                              00  0000000000  9                      05032     0139200170.                             00000000

>  
 BATCH     2401188850220240801073602051230240100750980000101002076        IT0000006570            251765330000   00000002401001646020240801   000000000000000000000000000000000000001000000081fcc082              00  0000000000  9                      05123     0085800050.                             00000000

Solution

  • Presumably, from your sample data, the startIndex argument on your SubString call should be 249:

    $sample = @'
               2401188832220240801083447050320240100750910000101002076        IT0000007994            251630830000   00000002401001652820240801   00000000000000000000000000000000000000                              00  0000000000  9                      05032     0139200170.                             00000000
    
    >
     BATCH     2401188850220240801073602051230240100750980000101002076        IT0000006570            251765330000   00000002401001646020240801   000000000000000000000000000000000000001000000081fcc082              00  0000000000  9                      05123     0085800050.                             00000000
    '@
    
    $sample.Substring(249, 5) # 05032
    

    You would need to also use -Raw on your Get-Content call to get the file content as a single multi-line string instead of an string array. So, in summary, the condition you're likely looking for should be:

    if ((Get-Content 'C:\appoggio\*.TXT' -Raw).Substring(249, 5) -eq '05032') {
        Set-Location C:\appoggio\prova -WhatIf
        Write-Warning 'ok'
    }
    

    You should also consider that this can get the content of multiple files since you're using a wildcard (*.txt) so this condition might fail in that case and there is likely a better way of doing this if you add more information to your question.