Equivalent of bash's `source` command in Powershell?

15

6

To run a bash script line-by-line (so as to preserve environment variables, for instance), one does the following:

$ . myscript.sh

Or:

$ source myscript.sh

I have a PowerShell script that - among other things - sets the value of the prompt via function called prompt. Simply running this script (".\myscript.ps1") does not change the prompt. However, running function line-by-line as a command does.

So what I effectively need is something like the source command for PowerShell. Is it possible?

EDIT: Should this post be moved to Stackoverflow?

Clarification 1: Since I run this function only on a need basis (i.e., not for every powershell session and/or always), I do not want to store in my powershell startup profile.

Sridhar Ratnakumar

Posted 2009-11-17T00:11:07.183

Reputation: 4 041

Note: your two Bash commands are different. You probably didn't mean to have the dot in the second one or you meant both of them to have "./" (current directory) at the beginning of the script name. – Paused until further notice. – 2009-11-17T13:24:16.050

Fixed it (by removing the dot) – Sridhar Ratnakumar – 2009-11-18T22:33:24.657

Answers

29

You can "dot source" in PowerShell as well. You just need to make sure that you specify the full path. So, if the script you want to load is in the local directory you would do:

PS C:\>. .\myscript.ps1

zdan

Posted 2009-11-17T00:11:07.183

Reputation: 2 732

1Is there anyway this could be done with an existing cmd script? Have a cmd script execution result in the powershell environment being modified? – peabody – 2015-11-04T19:43:24.387

1What if you need to run a .bat file and modify the environment? – Chloe – 2017-05-02T04:13:50.360

@chloe that's a whole other ball of wax. See this answer: http://stackoverflow.com/a/20078088/4304

– zdan – 2017-05-02T18:38:49.990

@zdan Seriously? Parse the .bat file? I think I'll just stop using PowerShell and go back to the DOS command prompt. – Chloe – 2017-05-04T05:54:34.327

THIS is the right answer :) dot sourcing in PowerShell works pretty much just like in Bash – Jaykul – 2009-11-17T04:30:53.837

I had no idea you could do that. nice. – DaveParillo – 2009-11-17T04:52:38.007

Whoa! How come I didn't try it before? :) – Sridhar Ratnakumar – 2009-11-18T22:25:03.287