Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One Powershell Script calling another with parameters

Tags:

powershell

I am attempting to call another PS script B.ps1 which takes a parameter:

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

Then in B.ps1:

Param([string]$ServerName)
...
...

When I attempt to execute Invoke-Expression, I get the following error:

The term 'C:\AzureFileShare\MEDsys\Powershell' is not recognized as the name of a cmdlet, function, script file, or operable program.

I don't know why PowerShell is complaining about this since the B.ps1 script does actually exist in the referenced folder. Unless something else is wrong?

like image 500
Randy Minder Avatar asked Nov 02 '17 12:11

Randy Minder


3 Answers

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
like image 115
henrycarteruk Avatar answered Oct 17 '22 13:10

henrycarteruk


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.

like image 14
Bill_Stewart Avatar answered Oct 17 '22 15:10

Bill_Stewart


Use dot sourcing

Like that:

."PathtoScript\script.ps1" "ParamValue"
like image 1
guiwhatsthat Avatar answered Oct 17 '22 14:10

guiwhatsthat