tags:

views:

170

answers:

3

How can I pre pend (insert at beginning of file) a file to all files of a type in folder and sub-folders using Powershell?

I need to add a standard header file to all .cs and was trying to use Powershell to do so, but while I was able to append it in a few lines of code I was stuck when trying to pre-pend it.

A: 

Have no idea, but if you have the code to append just do it the other way round. Something like

  1. rename existing file,
  2. create an empty file named the same as above
  3. append header to new empty file,
  4. append renamed file to previous,
  5. delete renamed file
agnul
A: 

Algorithmically talking , you don't really need a temporary file :

1)read the content of the file you need to modify

2)modify the content ( as a string , assuming you have the content in a variable named content ) , like this : content = header + content

3)seek to the beginning of the file , each language has a seek method or a seek equivalent

4)write the new content

5)truncate the file at the position returned by the file pointer

There you have it,no temporary file. :)

Vhaerun
+7  A: 

Here is a very simple example to show you one of the ways it could be done.

$Content = "This is your content`n"
Get-ChildItem *.cs | foreach-object { 
$FileContents = Get-Content -Path $_
Set-Content -Path $_ -Value ($Content + $FileContents)
}
Mark Schill