Forum Discussion

richardsmc's avatar
richardsmc
Copper Contributor
Jul 16, 2024
Solved

Help with Using PowerShell to split a file by a particular string and saving as specific name

Good afternoon,  I hope someone can assist.   I need assistance being able to split a file into multiple files with a specific name.   So  I use get-content to read the file 16/07/2024  Mess...
  • LainRobertson's avatar
    Jul 17, 2024

    richardsmc 

     

    Hi, Marvin.

     

    Here's a basic working template to get you started, where I've assumed the example data you've provided is consistently formed.

     

    If, for example, "MessageA" could in fact feature a space, such as "Message A", then some logic would have to be added to the script to allow for that.

     

    Input data file

     

    Script

    $SourceFile = "D:\Data\Temp\Forum\forum.txt";
    
    $SourceDirectory = [System.IO.Path]::GetDirectoryName($SourceFile) + "\";
    $FileOpen = $false;
    $Timestamp = [datetime]::MinValue;
    
    Get-Content -Path $SourceFile |
        ForEach-Object {
            $Line = $_;
    
            # Check this isn't empty space in between files. If so, skip it.
            if ((-not $FileOpen) -and [string]::IsNullOrWhiteSpace($Line))
            {
                # We do nothing here, meaning we skip the empty space between files.
            }
            # Check if we've hit a well-formed line that indicates the start of a new message-aligned file.
            elseif ((-not $FileOpen) -and
                    ($Line.Length -gt 10) -and
                    ([datetime]::TryParse($Line.Substring(0, 10), [ref] $Timestamp) -and
                    (4 -eq ($Parts = [regex]::Split($Line, "\s+")).Count)))
            {
                $NewFileName = [string]::Concat($SourceDirectory, $Parts[1], ".txt");
    
                Out-File -FilePath $NewFileName -InputObject $Line -ErrorAction:Stop;
                $FileOpen = $true;
            }
            # Check if we've hit a well-formed line indicating the end of a file.
            elseif ("*End of message" -eq $Line)
            {
                # This is more of a safety check, since outside of an error condition, $FileOpen should always be $true.
                if ($FileOpen)
                {
                    Out-File -FilePath $NewFileName -InputObject $Line -Append;
                }
    
                $FileOpen = $false;
                $NewFileName = $null;
            }
            # Otherwise, if a file is considered "open", weite the line to it. (Mechanically, the file isn't really open - it's just easier to conceptualise it that way.)
            elseif ($FileOpen)
            {
                Out-File -FilePath $NewFileName -InputObject $Line -Append;
            }
        }

     

    Output

     

    Cheers,

    Lain

Resources