Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Wednesday, July 1, 2009

Can I have a script know what folder it was executed from?

This is one that bugged me years ago when I first started scripting. The problem was portability. I was not able to easily move my scripts from one location to another without having to go in and change me code for any external files the script referenced.


I first started off using a constant in the declarations section of the script. This helped. I simply put the folder location the script was in and used that constant throughout the script. I still had to do manual work. Finally I got smart and asked Windows where the script was being executed from. Below is the code that I used.

Declaration section
Dim AppPath ' Will store the path that the script and text file are located in.

Script Main Logic

' Determin the file path
AppPath = fGetPath

Functions and Sub Procedures

Function fGetPath
' Returns the path that the script is run from.
Set oShell = CreateObject("WScript.Shell")
GetPath = oShell.CurrentDirectory & "\"
End Function ' GetPath

Using this code, your script will know where it is at and make it portable without having to worry about where the script is stored or executed from.

No comments: