Powershell – Copyright header generator script

Recently i have been doing pair programming with my colleague Andre and thanks to him, i learned powershell programming. Most of the code files in the project need some kind of copyright information at the top. One way to add these headers is by using code formatting tools like stylecop or resharper. But with my newly acquired skills i believe its better to write a small script to append the header on all code files using powershell.

Problem: (Add copyright information to all the files with a given extension found in the target and its subdirectories.)

  • Read all the files from target directory and its subdirectories with given extension.
  • Append header text at the beginning of the file with copyright information.

Solution:

param($target = "c:\\tmp", $companyname = "Lab49")
$header = "//-----------------------------------------------------------------------
// <copyright file=""{0}"" company=""{1}"">
//     Copyright (c) {1}. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------`r`n"
function Write-Header ($file) {
$content = Get-Content $file
$filename = Split-Path -Leaf $file
$fileheader = $header -f $filename,$companyname
Set-Content $file $fileheader
Add-Content $file $content
}
Get-ChildItem $target -Recurse | ? { $_.Extension -like ".txt" } | % {
Write-Header $_.PSPath.Split(":",3)[2]
}

About these ads

3 Responses to “Powershell – Copyright header generator script”

  1. Charlie Robbins Says:

    Neat. Definitely a good compliment to the VS snippet that I’ve got on my tools project:

    http://github.com/indexzero/dotnet-tools

  2. Leniel Macaferi (@johnleniel) Says:

    Hi Kishor,

    You really helped me! :)

    I posted a slightly modified version of your script here:

    http://www.leniel.net/2012/08/inserting-copyright-notice-banner-in-all-source-code-files-with-powershell.html

    Keep sharing…

    Best,

    Leniel

  3. Monty Says:

    Hey there! This post could not be written any better!
    Reading this post reminds me of my good old room mate!
    He always kept talking about this. I will forward this article to him.

    Pretty sure he will have a good read. Thank
    you for sharing!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: