Search code examples
powershellpowershell-2.0powershell-4.0

Adding text to a new line of existing file using Add-Content PowerShell


I am trying fetching content from a file using get-content and adding it to a existing file using add-content, but the issue is I am not able to add that content to new line. Can you please suggest on this?

Using below commands:

Get-content -Path $destRoot1 | Add-Content -Path $destRoot2 

Solution

  • I have solved it by using below trick:

    1.Add-Content -Path $destRoot2 "`n" 
    ##### I am adding new line character to existing file #####
    2.Get-content -Path $destRoot1 | Add-Content -Path $destRoot2 -Encoding UTF8
    ##### Appending data from $destRoot1 to $destRoot2 #####
    3.((Get-Content -Path $destRoot2) -notmatch '^\s*$' )| Select-Object -Unique | Set-Content -Path $destRoot2 -Encoding UTF8 
    ##### Using -notmatch '^\s*$' removing the blank line which I have added at line number 1 #####