I have been playing around unsuccessfully which is why I am here. I have a thousand .XML files in a folder. I am trying to add the line below to be the very first line in the file.
On one of my scripts I got close but really does not like that text for some reason. Can anyone help? really don’t want to sift through a thousand files to add this line manually.
Yes this is possible. Share what you have tried and what exactly isn’t working.
On another note, why exactly are you doing this? That line is an XML declaration that has valuable information for each specific XML file. Just going out and changing that line can break the xml files if they are using a different coding or are not standalone and linked to other XML files. What exactly are you attempting to solve?
Basically. I have a massive XML file and I’ve split each section out in to individual xml files. This has worked perfectly. However that header is missing from each file. Thats why I just need to add it in.
Ive rebooted my laptop since and didn’t save anything that was not working.
Funny, my Powershell ISE and and VSCode retains all of my code after a reboot, even if it’s not saved. Anywho, this is a simple process, all you need is to use Set-Content to overwrite the file:
#Get the files. You should make sure this is getting the files you want first. I normally would do the First 1 to test and validate and then run it on the rest.
$files = Get-ChildItem -Path C:\Scripts\*.txt # | Select -First 1
foreach ($file in $files) {
#Empty array
$content = @()
#Add first item in the array
$content += '<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>'
#Get Content get the content of the file seperated into an array.
#Next we append content of the file in the loop to the content array
$content += Get-Content -Path $file.FullName
#Here you need take the content and set it to overwrite the file, you should validate it looks correct
$content
}