Call PowerShell Scripts With Parameters, Functions, and Scope
You can run another PowerShell script from a PowerShell script with the call operator (&) and pass named parameters just as you would at the prompt. Use dot-sourcing (. followed by a path) when you need to import functions from another .ps1 file into the current script’s scope. The right choice depends on whether you want to run a separate task or reuse functions and variables.
Choose Between Running and Importing a Script
A .ps1 file can be either an executable task script or a library of reusable functions. Treating those two roles differently avoids scope surprises, accidental variable changes, and difficult-to-read code.
Use the call operator to run a task; dot-source only code you deliberately want to import.
| What You Need | Best Method | Result |
|---|---|---|
| Run another script and capture its output | Call operator: & |
The called script runs in its own child scope. |
| Pass named parameters to another script | Call operator with named parameters | PowerShell binds values to the child script’s param() block. |
Reuse a function defined in another .ps1 file |
Dot-sourcing: . |
Functions become available in the current script. |
| Import functions without allowing ordinary variables to affect the caller | Invoke-Command -ScriptBlock |
The import and function call run in a separate scope. |
| Start a completely separate PowerShell process | pwsh -File or powershell.exe -File |
The child has its own process, session state, and exit code. |
| Run a script on another computer | Invoke-Command -ComputerName |
PowerShell remoting runs the script remotely. |
Avoid Invoke-Expression for this job. It parses text as code, makes quoting harder, and creates an unnecessary injection risk when a script path or parameter value comes from outside your code.
Run Another Script With Parameters
Use the call operator when a parent script needs a child script to perform a task.
Step 1: Give the Called Script a Param Block
Put the parameters at the top of the child script. The script can output an object, string, or collection for the parent to capture.
Save this as Get-Report.ps1 in the same folder as the calling script:
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $Environment,
[switch] $IncludeDetails
)
$ErrorActionPreference = 'Stop'
[pscustomobject]@{
Environment = $Environment
DetailsIncluded = $IncludeDetails.IsPresent
Succeeded = $true
}
[CmdletBinding()] makes the script act more like an advanced PowerShell command, including support for common parameters such as -ErrorAction. Setting $ErrorActionPreference to Stop means a nonterminating error inside the child script becomes catchable by the parent.
Keep output intended for the caller on the success output stream. A bare object expression, Write-Output, or return sends data into that stream. Write-Host displays text on screen but is not a good way to return structured data.
Step 2: Call the Script With the Call Operator
In the parent script, construct a path based on $PSScriptRoot rather than the current working directory. $PSScriptRoot refers to the folder containing the current script, so the call keeps working even when someone starts the parent script from another location.
$reportScript = Join-Path -Path $PSScriptRoot -ChildPath 'Get-Report.ps1'
$result = & $reportScript -Environment 'Test' -IncludeDetails
The & character is the call operator. It tells PowerShell to execute the command or script whose path is stored in $reportScript.
The value emitted by Get-Report.ps1 is now in $result. You can use it as an object:
if (-not $result.Succeeded) {
throw "The report script did not complete successfully."
}
$result
A script invoked with & runs in a child scope. Its ordinary variables and functions do not become part of the parent script after it finishes.
Step 3: Use Splatting for Several Parameters
Splatting keeps a long call readable and makes it easier to add optional parameters later.
$reportArgs = @{
Environment = 'Test'
IncludeDetails = $true
}
$result = & $reportScript @reportArgs
The keys in $reportArgs must match parameter names in Get-Report.ps1. A hashtable key named Environment becomes -Environment; a key named IncludeDetails becomes -IncludeDetails.
Finish the method by checking the returned object or using the output in the next part of the parent script. Do not rely on visible console text as proof that a script succeeded.
Call a Function From Another PowerShell Script
Use dot-sourcing when the other .ps1 file is a function library rather than a task you want to launch and finish.
Put Reusable Functions in a Library Script
Save the following reusable function in Common.ps1:
function Get-ServerSummary {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $ComputerName
)
[pscustomobject]@{
ComputerName = $ComputerName
Reachable = $true
}
}
A function library should usually contain function definitions, comments, and safe initialization only. Do not put a task that should run automatically at the bottom of a file intended for dot-sourcing.
Dot-Source the Library and Call Its Function
The dot and the space are both required. The first dot is the dot-sourcing operator; it is not part of the file path.
. (Join-Path -Path $PSScriptRoot -ChildPath 'Common.ps1')
$summary = Get-ServerSummary -ComputerName 'web-01'
Dot-sourcing runs the external file in the current scope. After the first line, Get-ServerSummary behaves as though its function definition had been written directly in the calling script.
That convenience has an important consequence: variables assigned at the top level of Common.ps1 also enter the caller’s scope. If the library assigns $installerName and the parent already has a variable with that name, the imported assignment can replace the parent’s value. The same applies to aliases, functions, and other session-state changes made by the imported script.
Isolate an Imported Function Library When Needed
If you need a function from a file but do not want ordinary variables from that file to affect the caller, dot-source it inside a local Invoke-Command script block.
$libraryPath = Join-Path -Path $PSScriptRoot -ChildPath 'Common.ps1'
$summary = Invoke-Command -ScriptBlock {
param($Path)
. $Path
Get-ServerSummary -ComputerName 'web-01'
} -ArgumentList $libraryPath -ErrorAction Stop
Invoke-Command runs the script block in a separate scope. The function is available inside that block, and its output is returned to $summary, but normal variables created by Common.ps1 do not overwrite variables in the parent script.
This pattern is useful for older function libraries that contain unavoidable top-level assignments. For new code, a cleaner long-term fix is to keep reusable .ps1 libraries limited to function definitions.
Start a Separate PowerShell Process When Isolation Matters
Calling a script with & does not start another PowerShell process. It uses the current process and starts a child scope. That is usually faster and easier to debug.
Start a new process only when you deliberately need a fresh session, a different PowerShell edition, or a process-level exit code.
$workerScript = Join-Path -Path $PSScriptRoot -ChildPath 'Get-Report.ps1'
& pwsh -NoProfile -File $workerScript -Environment 'Test'
if ($LASTEXITCODE -ne 0) {
throw "The worker PowerShell process failed with exit code $LASTEXITCODE."
}
pwsh starts the PowerShell edition installed under the pwsh executable. On Windows systems where you intentionally need Windows PowerShell, use powershell.exe instead.
A separately started process has its own variables, loaded modules, profile state, and working environment. It also gives you a meaningful $LASTEXITCODE, which is why this pattern is appropriate for build scripts, CI jobs, and tools that use conventional process exit codes.
In this specific separate-process pattern, the child script can use exit to report success or failure. Do not use exit in a script called directly with &, because it can end the calling PowerShell session rather than simply returning control to the parent script.
Run a Script Remotely With PowerShell Remoting
To run a local script on another computer, use Invoke-Command with -ComputerName and -FilePath. The target machine must already allow PowerShell remoting, and your account must have permission to connect.
$reportScript = Join-Path -Path $PSScriptRoot -ChildPath 'Get-Report.ps1'
$result = Invoke-Command -ComputerName 'Server01' -FilePath $reportScript -ArgumentList 'Test'
-FilePath points to the script file on the computer starting the command. PowerShell sends the script content to the remote session and runs it there. Values in -ArgumentList are passed to the remote script’s param() block by position.
Use a simple parameter order for remote scripts, especially when the script must run from both local and remote callers. If you need richer remote behavior, such as credentials, persistent sessions, or multiple target computers, build and test the local version first.
Handle Output, Errors, and Exit Codes Correctly
A parent script needs a reliable way to distinguish a successful result from a failed task.
Return Data for Expected Results
For a directly called .ps1 script, return a structured object when the task completes.
[pscustomobject]@{
Succeeded = $true
Message = 'Report created'
}
The parent can capture that output with $result = & $scriptPath ... and inspect $result.Succeeded.
A function can return an exit-style value as well:
return $process.ExitCode
The caller captures it normally:
$ret = Install-Tool
For functions that wrap external installers or command-line tools, returning an integer exit code can be practical. For most PowerShell-to-PowerShell automation, an object with a success flag, message, and relevant output is easier to extend.
Throw Errors for Failed Work
Use throw when the child script cannot complete its job. The parent can catch that failure cleanly.
try {
$result = & $reportScript -Environment 'Test' -ErrorAction Stop
}
catch {
throw "Get-Report.ps1 failed: $($_.Exception.Message)"
}
The child script should use $ErrorActionPreference = 'Stop' or set -ErrorAction Stop on commands that otherwise emit nonterminating errors. Without that, an error may appear on screen while the script keeps running and the parent never enters its catch block.
Use $LASTEXITCODE for native executables, batch files, or a separate pwsh process. Do not treat it as the success status of a script called directly with &.
Confirm the Parent and Child Scripts Work Together
Before adding a child script to a larger automation workflow, verify these points:
- The child script has a
param()block for every value the parent supplies. - The parent uses
$PSScriptRootandJoin-Pathinstead of assuming the current directory. - A task script is called with
&; a function library is imported with.. - The called script returns only the data the parent needs on the success output stream.
- The child throws on an unrecoverable failure, and the parent catches or allows that error to stop the workflow.
- A directly called script does not use
exitfor ordinary success or failure reporting. - A dot-sourced library does not accidentally overwrite parent variables.
Test the parent script from a different working directory before relying on it in a scheduled task, build pipeline, or deployment process. That one check exposes many relative-path failures.
Frequently Asked Questions
How Do I Call a .ps1 File That Has No Parameters?
Use the call operator followed by the script path. The script runs in a child scope, and any success output is written to the parent pipeline.
$scriptPath = Join-Path -Path $PSScriptRoot -ChildPath 'Cleanup.ps1'
& $scriptPath
If Cleanup.ps1 outputs objects, capture them with $result = & $scriptPath.
How Do I Run a PowerShell Script From the Command Line?
Use pwsh -File to run a script from PowerShell 7 or later. The -File value is the script path, and remaining values can be passed as the script’s parameters.
pwsh -NoProfile -File .\Invoke-Report.ps1 -Environment Test
On Windows PowerShell, replace pwsh with powershell.exe when that edition is required.
How Do I Call a Batch Script From PowerShell?
On Windows, call a .cmd or .bat file with the same call operator used for other commands. Check $LASTEXITCODE afterward because batch files report status as process exit codes.
$batchScript = Join-Path -Path $PSScriptRoot -ChildPath 'Build.cmd'
& $batchScript
if ($LASTEXITCODE -ne 0) {
throw "Build.cmd failed with exit code $LASTEXITCODE."
}
Keep the batch script path in a variable rather than building a command string with Invoke-Expression.
Can I Use powershell.exe Instead of pwsh?
Yes. powershell.exe starts Windows PowerShell, while pwsh starts the newer cross-platform PowerShell edition. Use the executable that matches the modules, syntax, and runtime requirements of the child script.
powershell.exe -NoProfile -File .\Invoke-Report.ps1 -Environment Test
When possible, keep the parent and child on the same PowerShell edition so parameter binding, modules, and available language features remain predictable.
