Powershell append to file by joining two files

01 March,2017 by Jack Vamvas

 Question: Hi , I’d like to concatenate two text files  using Powershell.

Currently , the powershell code snippet below works by defining a file in a variable – and then using the foreach construct along with the get-content cmdlet to iterate through the list in the file.

 

$serverpath=”C:\servers.txt"

foreach ($instance in get-content $serverpath)
{
    $instance 
}

 

Now I have two text files – which I don’t have the option of merging as one file. So I’ll need to programmatically concatenate the files by some adjustments to the existing code.

How can introduce the second file , but not make many adjustments to the existing Powershell script?

 

Answer: There are a number of methods to concatenate to text files dynamically. I’ll offer one method based on the code snippet presented . On the assumption – it will cause minimal disruption.

An adjustment you could make is to extend the get-content cmdlet . So instead of referencing one variable , which you’ve added one file, you could reference two variables, which would reference two files.

In the example below, I've a) added a new variable $serverpathextra b) referenced the new variable through get-content

 

$serverpath=”C:\servers.txt"
$serverpathextra=”C:\serversExtra.txt”
foreach ($instance in get-content $serverpath,$serverpathextra)
{
    $instance 
}

 Read More

 Read a script file into Powershell CommandText with get-content ...

Compare two files with Powershell

Powershell Scripts for DBA

 


Author: Jack Vamvas (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on Powershell append to file by joining two files


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer