I am a complete newbie in Powershell scripting and programming. I need to do the Following:
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.....
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.....