Powershell function to add script to the profile

2011, Dec 01    

I’m currently in the middle of learning powershell; More specifically, on day 4 of the Microsoft 10325a Automating Administration with Windows Powershell 2.0.

With my coding background, i’ve tended to write most of the script inside functions to try and promote reuse.  I’ve found that maintaining a library of functions to be a bit of a headache so ended up writing the function below.  It’s by no means perfect (lets face it, PoSH is a little new to me currently… lets see how long before v2 makes it onto my blog), but it does the job.


function Add-CodeToProfile() {
  Adds a code snippet to your PoSH user profile 
  Ideally, you will want to add whole functions, not just one line scripts.
.PARAMETER Scriptblock
  A block of script that you want to save for future reuse
  If specified, a file will be created to store the script in. 
    [string]$usersProfilePSdir = "$env:userprofileMy Documentswindowspowershellv1.0";
    [string]$usersProfilePS1 = $usersProfilePSdir + 'profile.ps1';

    if(-not(Test-Path "$env:userprofileMy Documentswindowspowershell")) {new-item "$env:userprofileMy Documentswindowspowershell" -type directory}
    if(-not(Test-Path "$env:userprofileMy Documentswindowspowershellv1.0")) {new-item "$env:userprofileMy Documentswindowspowershellv1.0" -type directory}

    if(-not(Test-Path $usersProfilePSdir)) {
        #Add PS1
        new-item $usersProfilePSdir -type file
        #Add a line break at the end of the file
        "`r`n" >> $usersProfilePS1;

    #check filename
    if ($fileName -eq "") {
        #Add function to users profile
        $Scriptblock >> $usersProfilePS1
    else {
        #Add function to new file
        $newScriptFile = $usersProfilePSdir + $fileName + '.ps1';
        $Scriptblock >> $newScriptFile;

        #Add reference to profile
        '"' + $newScriptFile + '"' >> $usersProfilePS1