Search code examples
arrayspowershellcollectionsiterationpowershell-3.0

How to read the first element of all Rows in a text file and then iterate over it in Powershell scripting?


I am a complete newbie in Powershell scripting and programming. I need to do the Following:

  • There is text file which has number of rows, each row has elements separated by commas. Now, some rows always start with "BB" and there can be hundreds of "BB" rows. When its "BB", i need to do some changes etc.

I want to iterate over all the rows and if it starts with "BB", then i will do some stuff. Below is just a test code as I have no idea of what to do here. How, can i do it in most effective way, so that it is fast and has less performance overhead.

Update: Now, the issue is that the date in the first instance(its strange) of "BB" row is not getting updated. This is the updated code, i have written:

Now, should i write out-file after the "Foreach" loop as it will write to the file again and again. Also, when to use pipeline character (|).

$path = 'C:\CE\InputFile\file_test1.txt'
$Filedata = Get-Content $path

$CurrentDate = (Get-Date).ToString("yymmdd")

foreach($Row in $Filedata){
if($Row.split(",")[0] -eq "BB")
{
    $Row2Date = $Row.Split(",")[4] 
    $Temp = $Filedata -replace $Row2Date, $CurrentDate | 

Out-File C:\outdata\outputfile1.txt

}

}

AA, field1, field2, field3, field4, field5.....
BB, field1, field2, field3, field4, field5.....
CC, field1, field2, field3, field4, field5.....
DD, field1, field2, field3, field4, field5.....
BB, field1, field2, field3, field4, field5.....

Solution

  • As the requirements changed I post a new answer.
    Since you want to change the 5th field I extended the sample file

    ## Q:\Test\2018\04\30\SO_50095738_2.ps1
    $FilePath1 = 'C:\CE\InputFile\file_test1.txt'
    $FilePath2 = 'C:\outdata\outputfile1.txt'
    
    $FileData1 = Get-Content $FilePath1
    $CurrentDate = (Get-Date).ToString("yyMMdd")
    
    $FileData2 = ForEach($Row in $Filedata1){
        If ($Row.split(",")[0] -eq "BB"){
           $Row  -replace ($Row.Split(",")[4]), $CurrentDate
        } else {
           $Row
        }
    } 
    Out-File -FilePath $FilePath2 -InputObject $FileData2
    

    Sample output

    AA, field1, field2, field3, field4, field5.....
    BB, field1, field2, field3,180402, field5.....
    CC, field1, field2, field3, field4, field5.....
    DD, field1, field2, field3, field4, field5.....
    BB, field1, field2, field3,180402, field5.....