What is dot sourcing in PowerShell?

What is dot sourcing in PowerShell?

Q. What is dot sourcing in PowerShell?

A. Ordinarily when a script is executed it can be run as

.\script.ps1

This creates a child scope for the script however once the script completes any objects create are discarded, for example any variables created.

Alternatively you can dot source the script which will run in the current scope which means any variables etc will be maintained post script execution, e.g.

. .\script.ps1

You can easily test this. Save the following as script.ps1:

$answer="42"
write-output "ultimate answer is $answer"

Now see example execution:

PS D:\temp> .\script.ps1
ultimate answer is 42

PS D:\temp> $answer

PS D:\temp> . .\script.ps1
ultimate answer is 42

PS D:\temp> $answer
42

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish