Function to Add/Remove line(s) from text file – Feedback wanted

//Function to Add/Remove line(s) from text file – Feedback wanted
Function to Add/Remove line(s) from text file – Feedback wanted 2015-05-20T14:49:37+00:00

The Toolkit Forums Toolkit Extensions Function to Add/Remove line(s) from text file – Feedback wanted

  • Author
    Posts
  • macxcool
    Participant
    Post count: 23
    #245 |

    This function Adds a line to the end of a text file or Removes the first matching line or all matching lines from a text file either with a partial or complete match.
    I’m using Modify-TextFile because I can’t find a better verb. Update doesn’t seem to fit since this is not, necessarily about getting an up-to-date version of anything.

    <code>
    #region Function Modify-TextFile
    Function Modify-TextFile {
    &lt;#
    .SYNOPSIS
        Adds a line or removes a line from a text file.
    .DESCRIPTION
        Add a line to the end of a text file, or finds and removes a line from a text file.
    .PARAMETER Path
        Path to the text file
    .PARAMETER AddLine
        Switch to Add a line to a textfile
    .PARAMETER RemoveLine
        Switch to Remove a line/lines from a text file
    .PARAMETER Text
        Text to either Add to end of file or Search for and remove the first line that contains it.
    .PARAMETER Partial
        If RemoveLine switch is present. If True, searches for part of the line to remove, If False, searches for entire line. Default $false
    .PARAMETER Multiple
        If RemoveLine switch is present. If True, will remove all lines with Text. If False, removes only first matched line. Default $false
    .EXAMPLE
        Modify-TextFile -Path &#039;C:\Temp\TestFile.txt&#039; -AddLine -Text &#039;This is some text to append&#039;
    .EXAMPLE
        Modify-TextFile -Path &quot;$envWinDir\System32\TextFile.log&quot; -RemoveLine -Text &#039;Installation&#039; -Multiple $true
    .NOTES
        Created by tv45057 for the TVDSB Deployment team
    #&gt;
        [CmdletBinding()]
        Param (
            [Parameter(Mandatory=$true,HelpMessage=&#039;Please enter the complete path to the text file&#039;)]
            [ValidateNotNullorEmpty()]
            [string]$Path,
            [Parameter(Mandatory=$true,ParameterSetName=&#039;Add&#039;)]
    		[switch]$AddLine,
            [Parameter(Mandatory=$true,ParameterSetName=&#039;Remove&#039;)]
    		[switch]$RemoveLine,
            [Parameter(Mandatory=$true)]
            [ValidateNotNullorEmpty()]
            [string]$Text,
            [Parameter(Mandatory=$false,ParameterSetName=&#039;Remove&#039;)]
            [ValidateNotNullorEmpty()]
            [boolean]$Multiple = $false,
            [Parameter(Mandatory=$false,ParameterSetName=&#039;Remove&#039;)]
            [ValidateNotNullorEmpty()]
            [boolean]$Partial = $false
        )
    
        # Check to see if text file exists
        If (Test-Path -Path $Path -PathType Leaf) {
            If ($AddLine) {
                Write-Log -Text &quot;Append text &quot;&quot;$text&quot;&quot; to [$path]...&quot; #-Source {$CmdletName}
                # Begin process of adding a line to the end of the file. We&#039;re assuming a Windows-formatted file right now
                Add-Content -Path $Path -Value &quot;$Text&quot;
            }
            ElseIf ($RemoveLine) {
                Write-Log -Text &quot;Remove text &quot;&quot;[$text]&quot;&quot; from [$path]...&quot;
                # Begin the process of finding and removing a line/lines from the file
                $TempPath = $Path + &#039;.temp&#039;
                # Make backup of text file - remove current backup if it exists
                $BackupPath = $Path + &#039;.backup&#039;
                If (Test-Path -Path $BackupPath -PathType Leaf) {
                    Remove-File -Path $BackupPath
                }
                Copy-File -Path $Path -Destination $BackupPath
    
                If ($Multiple -eq $true) {
                    # Remove lines with multiple instances of text from file
                    If ($Partial -eq $true) {
                        # Remove multiple lines with instances of partial string
                        $Contents = Get-Content $Path | Where-Object {$_ -notmatch $Text}
                        If ($Contents) {
                            Set-Content $TempPath
                        }
                        Else {
                            echo $null &gt;&gt; $TempPath
                        }
                    }
                    ElseIf ($Partial -eq $false) {
                        # Remove multiple lines with complete string match
                        $Contents = Get-Content $Path | Where-Object {$_ -notlike $Text} 
                        If ($Contents) {
                            Set-Content $TempPath
                        }
                        Else {
                            echo $null &gt;&gt; $TempPath
                        }
                    }
                }
                ElseIf ($Multiple -eq $false) {
                    # Remove single line from text file
                    If ($Partial -eq $true) {
                        # Get index of first matching line with partial string match
                        $intLine = (Get-Content $Path | Where-Object {$_ -match $Text} | Select-Object -First 1).ReadCount                            
                    }
                    ElseIf ($Partial -eq $false) {
                        # Get index of first matching line with complete string match
                        Write-Host &#039;multiple-false partial-false&#039;
                        $intLine = (Get-Content $Path | Where-Object {$_ -like $Text} | Select-Object -First 1).ReadCount
                    }
                    If ($intLine -gt 0) {
                        Write-Log -Text &quot;Replacing [$Text] in line [$intLine]&quot;
                        $fileContents = Get-Content $Path
                        $fileContents.Item($intLine-1) = &quot;&quot; # modify the array item found above - replace with empty string
                        $fileContents | Set-Content $TempPath
                    }
                    Else {
                        # No matchine line
                        Write-Log -Text &quot;[$text] not found in [$path]&quot;
                            
                    }
                }
                # Remove original File and rename Temp file to match
                If (Test-Path -Path $TempPath -PathType Leaf) {
                    Remove-File -Path $Path
                    Rename-Item -Path $TempPath -NewName $Path
                }
            }
        }
        Else {
            # There is no such file - abort function
            Write-Log -Text &quot;File [$Path] does not exist...&quot;
        }
    }
    #endregion
    </code>
    • This topic was modified 2 years, 6 months ago by  macxcool.

You must be logged in to reply to this topic.