Including external powershell scripts

2
Jul
1

I struggled getting this to work for quite some time. All the posts I found online made it way confusing so I am going to try to clarify it here. You include external powershell files like so

.  C:\mydir\powershellfile.ps1

easy enough. The period in the front is like your include statement in other languages and YES there is a space between the period and the C:\. If your include file is in the same directory you can do a relative path like so

. .\powershellfile.ps1 (.<space>.\powershellfile.ps1)

notice the space! This is where I got lost. There must be a space between these periods. Do not if you want to autorun your powershell file relative paths usually want work. In order to do this you must create a .bat file that will execute your powershell file. When the .bat file does this the powershellfile is executing from the .bat location, or at least that is what I come to determine. So in order to get around this and make my life of managing these scripts easier I created a variable to hold the absolute path as such

$this_path = C:\mydir
. $this_path\powershellfile.ps1 #this includes the file with a absolute path

so far this is working great for me and should make it much easier if I ever need to move the script.


1 Comment

  1. Adam bell
    10:19 pm on July 2nd, 2009

    Gday Kevin,

    Dot sourcing can be a bit confusing. I generally perform an include like this:
    # HP AS password management
    . lib\hp-pwd.ps1

    # MS Active Directory Permissions
    . lib\DSperms.ps1

    with my generic functions stored in the “lib” sub-folder to the parent script.

    If you prefer to use variables, Jeffrey has a pretty funky function that works really well: http://blogs.msdn.com/powershell/archive/2007/06/19/get-scriptdirectory.aspx

    Just beware trying to use it from within PowerGUI as it currently doesn’t work as expected.

    Cheers,
    Adam :)

Leave a comment

RSS feed for comments on this post