一个 Powershell 脚本使用参数调用另一个 [英] One Powershell Script calling another with parameters
问题描述
我正在尝试调用另一个带有参数的 PS 脚本 B.ps1
:
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"
然后在B.ps1
:
Param([string]$ServerName)
...
...
当我尝试执行 Invoke-Expression
时,出现以下错误:
When I attempt to execute Invoke-Expression
, I get the following error:
术语C:\AzureFileShare\MEDsys\Powershell"未被识别为 cmdlet、函数、脚本文件或可运行程序的名称.
The term 'C:\AzureFileShare\MEDsys\Powershell' is not recognized as the name of a cmdlet, function, script file, or operable program.
我不知道为什么 PowerShell 会抱怨这个,因为 B.ps1
脚本确实存在于引用的文件夹中.除非有其他问题?
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?
推荐答案
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
这篇关于一个 Powershell 脚本使用参数调用另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!