. (source or dot operator)

When you dot source a script (or scriptblock), all variables and functions defined in the script (or scriptblock) will persist in the shell when the script ends.

      . filename [arguments]

      .{ scriptblock } 

   filename    The path and filename of the script to run.

   arguments   Any arguments for the script.

When a script is Dot-Sourced in the current scope, any functions, aliases, and variables that the script creates become available in the current scope.

To dot-source a library script in the same directory as the currently running script, we can use the $MyInvocation Automatic Variable to work out the directory (we can’t always assume this will be the current directory):

function Get-ScriptDirectory
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path

In PowerShell 3 and above this can be simplified to just:
 . "$PSScriptRoot\scripttorun.ps1"

To start PowerShell and dot source a script:

powershell -command ". c:\demo\script.ps1"
powershell -file c:\demo\script.ps1

Dot Sourcing vs Call

Dot sourcing runs a function or script within the current scope.
unlike the call operator (&) which will run a function or script, but it is not added to the current scope.

PS C:\> $x=1
PS C:\> &{$x=2};$x
PS C:\>
. {$x=2};$x


Dot sourcing a script:

PS C:\> . C:\scripts\myscript.ps1

Dot sourcing a script in the current directory:

PS C:\> . ./script64.ps1

Contrast these two snippets of PowerShell using scriptblocks:

PS C:\> $n = 1;&{$n = 2};$n
PS C:\> $n = 1;.{$n = 2};$n

#If dogs run free, why not me, Across the swamp of time?, My mind weaves a symphony, And tapestry of rhyme# ~ Bob Dylan

Related PowerShell Cmdlets

& Call Operator - execute a command, script or function.
How-to: PowerShell Operators
How-to: Run a PowerShell script
Invoke-Item - Invoke an executable or open a file.

Copyright © 1999-2024 SS64.com
Some rights reserved