且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一个 Powershell 脚本使用参数调用另一个

更新时间:2023-01-08 16:55:16

dot-sourcing the script 如我的原始答案所示,将脚本和变量、对象、函数等加载到当前会话中 - 这可能在某些情况下会产生意想不到的后果.

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

问题是您的文件路径中有一个空格,因此您需要将整个路径用单引号括起来,以便正确识别.(参见 about_Quoting_Rulesa> 有关单引号和双引号的更多信息).它最终成为一个凌乱的命令:


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 更好,因为您只需将脚本路径用双引号括起来并保持原样:

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