Advertisement
anonit

Prepend data to each line in text file

Jan 18th, 2016
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ##Prepend-Line.ps1
  2.  
  3. ## Will take a string and prepend each line of a file and output to a different file.
  4. ## eg
  5. ## Given a file containing 3 lines called infile.txt:
  6. ## line 1
  7. ## line 2
  8. ## line 3
  9.  
  10. ## using the command "Prepend-Line.ps1 -infile infile.txt -prepend asdf -outfile outfile.txt
  11. ## will create a file called outfile.txt containing:
  12. ## asdfline 1
  13. ## asdfline 2
  14. ## asdfline 3
  15.  
  16. ## Usage:
  17. ## Prepend-Line.ps1 -infile %PATHTOFILETOREAD% -prepend %STRINGTOPREPEND% -outfile %PATHTOFILETOWRITE%
  18. ## -infile is the file to read
  19. ## -prepend is the string data to add to the front of each line
  20. ## -outfile is the file to write - if the file exists it will be overwritten
  21.  
  22. ## eg:
  23. ## Prepend-Line.ps1 -infile c:\logs\monday.txt -prepend "Monday 18/01/2016" -outfile c:\logs\modmonday.txt
  24.  
  25.  
  26. param(
  27.     [string]$infile=$(throw "-infile parameter is required"),
  28.     [string]$prepend=$(throw "-prepend parameter is required"),
  29.     [string]$outfile=$(throw "-outfile parameter is required")
  30. )
  31.  
  32. $newfile=$null
  33. $wholefile=get-content $infile
  34.  
  35. foreach($line in $wholefile)
  36. {
  37.     $newline=$Prepend+$line
  38.     $newfile=$newfile+$newline+"`n"
  39. }
  40.  
  41. $newfile | out-file $outfile
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement