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

Viewed 131

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 
2 Answers

You need to set the content to the destination file path and not add content. Refer the change below:

$destRoot1 = "C:\File\path1.txt"
$destRoot2 = "C:\destination\path\of\the\file.txt"
Get-content -Path $destRoot1 |Set-Content -Path $destRoot2 -Force

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 #####
Related