One Powershell Script calling another with parameters

EDIT: dot-sourcing the script as shown in my original answer will load the script and variables, objects, functions, etc. into the current session - this might have unintended consequences in certain circumstances.

The alternative is to use the & call operator which runs the script in its own scope:

& "C:\AzureFileShare\MEDsys\Powershell Scripts\B.ps1" -ServerName medsys-dev

The problem is you have a space in your file path so you need to wrap the entire path in single quotes so it's recognised correctly. (See about_Quoting_Rules for more info on single vs double quotes). It ends up being a messy command in the end:

Invoke-Expression "&'C:\AzureFileShare\MEDsys\Powershell Scripts\B.ps1' -ServerName medsys-dev"

dot-sourcing is much nicer as you just wrap the script path in double quotes and leave the params as-is:

."C:\AzureFileShare\MEDsys\Powershell Scripts\B.ps1" -ServerName medsys-dev

You don't need Invoke-Expression or dot-sourcing. Just run the script:

& "C:\AzureFileShare\MEDsys\Powershell Scripts\B.ps1" -param1 arg1...

If the script's path and/or filename contain spaces, enclose the script in quotes and use the & (call) operator to run the script. If the script's path and/or filename does not contain quotes, you can run it without the quotes or the & operator:

C:\AzureFileShare\MEDsys\PowershellScripts\B.ps1 -param1 arg1...

The reason I don't recommend dot-sourcing the script is because the variables, functions, etc. from the script will appear in the current session. This is probably not the intent if you just want to run the script and not pollute the current session's namespace with stuff from the script.

Tags:

Powershell