使用来自其他PowerShell脚本的参数调用PowerShell脚本

Chr*_*s L 12 powershell

如何调用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
Run Code Online (Sandbox Code Playgroud)

bar.ps1

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

Invoke-Expression $cmd $args
Run Code Online (Sandbox Code Playgroud)

错误:

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

这是我最近的尝试 - 我尝试过googling的多种方法似乎没有用.

如果我从shell终端运行foo.ps1,因为./foo.ps1 -a 'arg1' -b 2它按预期工作.

Chr*_*s L 19

在发布问题之后,我偶然发现了答案.为了完整性,这里是:

bar.ps1:

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

Invoke-Expression "$cmd $args"
Run Code Online (Sandbox Code Playgroud)


小智 8

以下内容可能对未来的读者有所帮助:

foo.ps1:

param ($Arg1, $Arg2)
Run Code Online (Sandbox Code Playgroud)

确保将“param”代码放在任何可执行代码之前的顶部。

bar.ps1:

& "path to foo\foo.ps1" -Arg1 "ValueA" -Arg2 "ValueB"
Run Code Online (Sandbox Code Playgroud)

就是这样 !