Executing another Powershell script
Published on: 16th Dec 2019
Updated on: 3rd Aug 2025
Explanation
To run a Powershell script file in the current directory.
.\test1.ps1
Write-Output "done"
To run a Powershell script file name that is stored in the same script location while the script file name is kept in a variable. In that you can you need to use &
symbol to invoke the script.
$ps_file = "$PSScriptRoot\test1.ps1"
& $ps_file
Write-Output "done"
Notes
&
symbol lets you to execute a command, script file or script block.
Use case
-
If you are managing multiple servers and each has a slightly different setup, you may want to have different script files for different servers.
To do this, you will have to compare the server name and then decide which script to run. The server name can be retrieved from
$env:computername
. For example,if ($env:computername -eq "my-server-01") { Write-Output "run script-01.ps1" } else { Write-Output "run script-02.ps1" }
-
If you are managing multiple applications that require sophisticated maintenance scripts.
-
Some scripts were developed by third parties and you don't want to merge their codes into yours.
Back to #POWERSHELL blog
Back to #blog listing