01 March,2017 by Tom Collins
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 a script file into Powershell CommandText with get-content ...
Compare two files with Powershell
This is only a preview. Your comment has not yet been posted.
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.
Posted by: |