I want to combine the content of all the files in my subfolders in one file. However, I want to exclude the root folder from this search.
I'm very close with the following command:
Get-ChildItem -include *.sql -rec | ForEach-Object {gc $_; ""} | out-file final.sql
The problem is that, as the foreach is recursive, it also finds out the output file (final.sql), which creates an infinite loop. This powershell commands never ends and the final.sql file gets larger and larger with time.
How can I exclude the current directory from my search?
Important: I don't want to explicitly mention the path, as different users will have a different file system.
Try this:
$mainPath = 'C:\files\test'
$directories = Get-ChildItem -Path $mainPath -Directory
$destFile = $mainPath + '\final.sql'
Remove-Item -Path $destFile -ErrorAction SilentlyContinue | Out-Null
foreach( $directory in $directories ) {
Get-ChildItem -Path $directory.FullName -include *.sql -rec | ForEach-Object {gc $_; ""} | Out-File $destFile -Append
}