Another interesting scripting day for Powershell Kid and suddenly he is stuck at a simple problem. He can’t keep mentioning the full directory path every time explicitly in the script. Because, next minute if he moves the script to some other location, the script fails!! Let’s look into the problem he is facing.

Powershell Kid creates an awesome script which uses few other files for input and output. So his script is saved at

D:My Test ScriptsThe Crazy ScriptCrazyPS.ps1

and the script uses external files for input and output purpose, something like

-----
-----
$inputcontent = Get-Content "D:My Test ScriptsThe Crazy Scriptbininput.txt"
-----
-----
$output >>  "D:My Test ScriptsThe Crazy Scriptbinoutput.txt"

 

Now the script executes marvelously, and the Powershell Kid goes the EUREKA!! mode.

Now he moves the script folder “The Crazy Script” to his favourite folder

"C:My Fav ScriptsThe Crazy Script"

and executes it again from the new location. Disaster! It throws errors like flying dishes. What should he do now?

 

Solution

Hey Powershell Kid, don’t use full directory paths, rather use relative paths. At the beginning of the script mention the following line:

$ScriptPath = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent

Now you can refer this variable as the relative path, like:

-----
-----
$inputcontent = Get-Content "$ScriptPathbininput.txt"
-----
-----
$output >>  "$ScriptPathbinoutput.txt"

Have a fun day scripting!!

Advertisements