从另一个PowerShell脚本中使用参数调用PowerShell脚本

19
如何在PowerShell脚本内部调用一个接受命名参数的PowerShell脚本?
foo.ps1:
param(
[Parameter(Mandatory=$true)][String]$a='',
[Parameter(Mandatory=$true)][ValidateSet(0,1)][int]$b, 
[Parameter(Mandatory=$false)][String]$c=''
)
#stuff done with params here

bar.ps1

#some processing
$ScriptPath = Split-Path $MyInvocation.InvocationName
$args = "-a 'arg1' -b 2"
$cmd = "$ScriptPath\foo.ps1"

Invoke-Expression $cmd $args

错误:

Invoke-Expression : A positional parameter cannot be found that accepts 
argument '-a MSFT_VirtualDisk (ObjectId = 
"{1}\\YELLOWSERVER8\root/Microsoft/Windo...).FriendlyName -b 2'

这是我最新的尝试 - 我尝试了多种方法,通过谷歌搜索,但似乎都无法解决问题。

如果我在shell终端中使用./foo.ps1 -a 'arg1' -b 2运行foo.ps1,它按预期工作。


1
虽然您已经找到了解决此特定问题的答案,但最佳实践建议在文件中使用函数而不是“松散代码”,甚至更好的做法是使用模块(.psm1 文件)。并且尽量避免使用 Invoke-Expression(请参阅 Invoke-Expression 被认为是有害的)。 - Michael Sorens
2个回答

25

发布问题后,我偶然发现了答案。为了完整起见,在此提供答案:

bar.ps1:

#some processing
$ScriptPath = Split-Path $MyInvocation.InvocationName
$args = @()
$args += ("-a", "arg1")
$args += ("-b", 2)
$cmd = "$ScriptPath\foo.ps1"

Invoke-Expression "$cmd $args"

你的答案中有语法错误 - 在这一行 $args += ("-b" 2) 中缺少 "-b" 和 2 之间的逗号。 - honzakuzel1989
选择参数“-b”的值2不合适,因为foo.ps1包含ValidateSet值0,1。 - honzakuzel1989
1
很好,干净利落 :). 浪费了很多时间尝试传递参数 :/. - Drasius
1
我有一个参数$dirPath,其中路径中包含空格。例如:"D:\work dir\app"。当像这样传递时,它会抛出一个错误: $args += ("-appDir", "$dirPath")。 我得到的错误是:"The term 'D:\work' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." 如何处理带有空格的路径? - Drasius
我尝试了这个页面https://dev59.com/8mMl5IYBdhLWcg3wRlPo中建议的解决方案('Set-Location' ..)。 - Drasius
注意:$args 是一个自动变量,不应该用作变量名。此外,Invoke-Expression 存在漏洞,应该使用调用运算符 & - Maximilian Burszley

8

以下内容或许对未来读者有所帮助:

foo.ps1:

param ($Arg1, $Arg2)

请确保将“param”代码放置在任何可执行代码之前。

bar.ps1:

& "path to foo\foo.ps1" -Arg1 "ValueA" -Arg2 "ValueB"

就是这样!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接