Wednesday 7 November 2018

Bulk combine content of files

The following PowerShell code was developed to copy the content of multiple .xml files and combine them into a single .txt file. At the time this was for a number of EndNote references which needed to be imported into the application.

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
#Looks for a folder called 'XML' in current working location (or PowerShell directory). Pipes this through to filter .xml files only, then pipes this again to get the raw file content (keeps any white space within the file).
$XMLFolder = Get-ChildItem -Path ((Get-Location).Path + '\XMLs') | Where-Object { $_.Extension -match ".xml" } | Get-Content -Raw

#Check a combined file does not already exist (this was to prevent a user from overriding anything they already had). If file does not exist then create it (hiding 'New-Item' output via 'Out-Null' to simply avoid clogging the console window).
If (-Not(Test-Path ($CombinedFile = ((Get-Location).Path + '\Combined.txt')))) {
    New-Item -ItemType File -Path "$CombinedFile" | Out-Null

    #Add content of .xml files to .txt file
    $XMLFolder | Add-Content $CombinedFile
    Write-Host 'Task successfully completed.' -ForegroundColor Green
}
Else {
    Write-Host "$CombinedFile already exists, please delete." -ForegroundColor Red
}
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

Bulk combine content of files.ps1

No comments:

Post a Comment