Powershell别名、参数化函数

问题描述 投票:0回答:1

我有一个应用程序可执行文件

say.exe
可以用指定的语言来表达字符串。我重复运行的一些命令:

> c:\say.exe --voice 11 "that's wicked, innit" # say sentence out loud in English.
> c:\say.exe --voice 7 "Mamma, voglio la pasta." # say sentence out loud in Italian
...

我想要一个别名,这样我就不用指定

--voice X
参数并将句子放在引号中

> say_en that''s wicked, innit.
> say_it Mamma, voglio la pasta.
...

尝试

Set-Alias -Name say_en -Value "c:\say.exe --voice 11"

创建成功。运行时失败

术语“c:\say.exe --voice 11”未被识别为 cmdlet 的名称,...

哦,你需要创建一个函数

Function sayWithVoice7 {
    C:\say.exe --voice 7 "$args"
}
Set-Alias -Name say_it -Value sayWithVoice7

Function sayWithVoice14 {
    C:\say.exe --voice 14 "$args"
}
Set-Alias -Name say_en -Value sayWithVoice14
...

但现在我有 N 个别名的 N 个函数。

我想要一个参数化函数

Function sayWithVoice {
    Param ($voice_id)
    C:\say.exe --voice $voice_id "$args"
}
Set-Alias -Name say_en -Value sayWithVoice 11 # wrong way to pass 11
Set-Alias -Name say_it -Value sayWithVoice 7 # wrong way to pass 7
....

但它不允许我从别名定义中将参数传递给

sayWithVoice
。试过
sayWithVoice(11)
,没用。

如何将参数 11 传递给

sayWithVoice

powershell
1个回答
0
投票

您可以使用哈希表将国家/地区代码映射到语音标识符,然后通过写入

function:
驱动器以编程方式创建包装函数:

$voiceMap = @{
  en = 11
  it = 7
  # ... and so on
}

foreach ($pair in $voiceMap.GetEnumerator()) {
  Set-Content -Path "function:\say_$($pair.Name)" -Value "& say.exe --voice $($pair.Value) ""`$args"""
}

您现在定义了两个函数:

say_en
say_it

© www.soinside.com 2019 - 2024. All rights reserved.