Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 34 ยท Functions and Scripts

Scripts and Execution Policy

Learn to save PowerShell code as .ps1 scripts, run them with the call operator, dot source libraries, use $PSScriptRoot, and understand execution policy.

Typing commands is fine for a quick job. When you want to repeat the work, share it or schedule it, you save the commands in a script: a plain text file with the extension .ps1. This lesson shows how to run scripts, how to load functions from one script into another, how to find files relative to the script and what the execution policy does.

It also clears up a common misunderstanding. The execution policy is a safety feature that stops you running unexpected scripts by accident. It is not a security boundary, and this lesson explains why.

The commands here are read-only because the site cannot run a PowerShell host or touch your files. The runnable examples are JavaScript stand-ins: one models how a policy decides, and one models dot sourcing versus the call operator. They are models, and the lesson says so each time.

Writing and running a script

A script is just commands in a file. Save this as hello.ps1:

POWERSHELL
param(
    [string]$Name = 'world'
)

"Hello, $Name from $PSCommandPath"

A param( ) block at the top of a script works like the one in a function, so the script accepts arguments. To run it from its folder:

POWERSHELL
.\hello.ps1
.\hello.ps1 -Name Ada

The leading .\ is required. PowerShell does not search the current folder when you type a bare name, which prevents a hostile dir.ps1 in some folder from replacing a real command. If the path contains spaces, quote it and use the call operator &, which means "run this string as a command":

POWERSHELL
& 'C:\Tools\My Scripts\backup.ps1' -Target D:\
$tool = 'C:\Tools\sync.ps1'
& $tool -Verbose

From another program, such as Task Scheduler or a batch file, start a new PowerShell and point it at the file:

POWERSHELL
pwsh -NoProfile -File C:\Tools\backup.ps1 -Target D:\
powershell.exe -NoProfile -File C:\Tools\backup.ps1

-File runs the script and passes the remaining text as arguments. -Command instead treats its text as PowerShell code, which is useful for one-liners but needs careful quoting. -NoProfile skips your profile so the run is predictable, as explained in Modules and Profiles.

Script scope, dot sourcing and the call operator

A script runs in its own scope, like a function. Variables and functions it defines disappear when it ends. That is usually what you want, but a library of helper functions needs the opposite. Dot sourcing runs a script in the current scope, so everything it defines stays.

POWERSHELL
# helpers.ps1
function Get-Banner { param($Text) '=== ' + $Text + ' ===' }
$defaultColor = 'Cyan'
POWERSHELL
& .\helpers.ps1          # runs in a child scope; the function is gone afterwards
Get-Banner 'hi'          # error: the term is not recognized

. .\helpers.ps1          # dot, space, path: runs in the current scope
Get-Banner 'hi'          # === hi ===
$defaultColor            # Cyan

There must be a space between the dot and the path. .\helpers.ps1 with no space is a normal run, and . .\helpers.ps1 is a dot source.

Three ways to start a script

.\script.ps1 Runs in its own scope. Variables vanish afterwards.
Call operator Runs a path in a variable or with spaces. Also a child scope.
Dot sourcing Runs in your scope. Functions and variables stay.

Dot source libraries, call everything else.

1 / 2

Paths relative to the script

When a script reads a config file or imports a helper, the current folder is whoever launched it, not where the script lives. Use the automatic variable $PSScriptRoot, which is the folder that holds the running script.

POWERSHELL
. (Join-Path $PSScriptRoot 'helpers.ps1')
$config = Get-Content -Raw (Join-Path $PSScriptRoot 'settings.json') | ConvertFrom-Json

$PSCommandPath gives the full path of the script itself. Both are empty at an interactive prompt, so test scripts as files rather than by pasting. For the file commands used above, see Working with Files and Folders.

Here is a stand-in for the scope rule. Each script is a function that either returns its definitions to be merged into the caller (dot source) or throws them away (call operator).

JS Dot sourcing versus the call operator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Execution policy

When you start a script on Windows, PowerShell checks the execution policy first. It decides which scripts may run, based mostly on whether they are signed and where they came from.

Policy Meaning
Restricted No script files run. Only interactive commands. This is the default for Windows PowerShell 5.1 on client versions of Windows.
AllSigned Every script must be signed by a publisher you trust.
RemoteSigned Scripts you wrote locally run; scripts that came from the internet must be signed. The default for PowerShell 7 on Windows and for Windows Server.
Unrestricted All scripts run, with a prompt for ones downloaded from the internet.
Bypass Nothing is blocked and there are no prompts or warnings.
Undefined No policy set in that scope.

A script is "from the internet" when it carries a Mark of the Web, a hidden stream Windows adds to files that browsers and many mail or chat clients download. You can remove the mark from a file you have reviewed with Unblock-File.

POWERSHELL
Get-ExecutionPolicy                    # the effective policy
Get-ExecutionPolicy -List              # every scope and its setting
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Unblock-File .\downloaded-tool.ps1

The policy can be set in several scopes, and the first one with a value, from the top, wins: MachinePolicy and UserPolicy (Group Policy), then Process (this session only), CurrentUser and finally LocalMachine. -Scope CurrentUser needs no administrator rights, so it is the usual choice for a personal machine. On Linux and macOS the execution policy is not enforced.

Why it is not a security boundary

Microsoft documents this plainly: the policy helps users avoid accidental runs. A determined user can start another session with -ExecutionPolicy Bypass, paste the script text into a prompt, or read the file and run its contents. So do not rely on it to stop an attacker. Real protection comes from application control (such as AppLocker or App Control for Business), constrained language mode, least privilege and review, which Security and Secrets covers.

Signing basics

Signing proves who published a script and that it has not changed since. You need a code-signing certificate that your machines trust.

POWERSHELL
$cert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Select-Object -First 1
Set-AuthenticodeSignature -FilePath .\deploy.ps1 -Certificate $cert
Get-AuthenticodeSignature .\deploy.ps1      # Status: Valid, HashMismatch, NotSigned ...

A signature block is added as a comment at the end of the file. Editing any character afterwards makes the signature invalid until you sign again, which is the point.

Group Policy can set MachinePolicy or UserPolicy. When it does, Set-ExecutionPolicy fails with a message that the setting is overridden, and only an administrator of the policy can change it.

A policy decision model

The next example models the Windows decision. It is a simplified teaching model: it reads a policy name, whether the script has the Mark of the Web and whether it has a valid signature from a trusted publisher, and reports allow, prompt or block. The real engine has more detail, such as per-scope lookup and certificate chain checks.

JS Would this script run?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Good habits for scripts

  • Start every script with a param( ) block instead of reading $args.
  • Use $PSScriptRoot for paths to files shipped with the script.
  • Dot source only trusted libraries, because they run with your rights in your scope.
  • Run with -NoProfile from schedulers so a profile cannot change the result.
  • Review scripts you download before running them, and unblock a file only after you have read it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You saved tools.ps1 in the current folder. Which command runs it?

    PowerShell does not search the current folder for bare names. You must give a path, so .\tools.ps1 works.
  2. 2. How is . .\helpers.ps1 different from & .\helpers.ps1?

    Dot sourcing runs a script in the caller's scope. The call operator uses a child scope that is discarded.
  3. 3. Under RemoteSigned, which script is blocked?

    RemoteSigned requires a trusted signature only for scripts that came from the internet. Local scripts may be unsigned.
  4. 4. Why should you not rely on execution policy as a security boundary?

    Execution policy guards against accidents. It is easy to bypass, so use application control, constrained language mode and least privilege for real protection.
  5. 5. Which variable gives the folder that contains the running script?

    $PSScriptRoot is the script's own folder. $PWD is the current location, which depends on who launched the script.

Summary

  • A script is a .ps1 file. Run it with a path such as .\script.ps1, or with & for quoted paths and variables.
  • A script and & use their own scope. Dot sourcing (. .\file.ps1) runs in the current scope, which is how you load function libraries.
  • $PSScriptRoot and $PSCommandPath locate files relative to the script.
  • Execution policy (Restricted, AllSigned, RemoteSigned, Unrestricted, Bypass) is set per scope. It guards against accidents and is not a security boundary.
  • Signing proves origin and integrity. Editing a signed file breaks the signature.

Next, organize and share your functions with Modules and Profiles.