我希望能够使用函数简化 AzureCLI 任务中的一些内联 powerscript,类似于以下内容:
- task: AzureCLI@2
displayName: "My Task"
inputs:
scriptType: pscore
scriptLocation: inlineScript
inlineScript: |
Do-Something "hello" "world"
Do-Something "goodbye" "world"
function Do-Something {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $Hello,
[Parameter(Mandatory=$true, Position=1)]
[string] $World
)
Write-Host "$Hello $World"
}
但是失败并出现以下错误:
+ Do-Something "hello" "world"
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (Do-Something:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException
##[error]Script failed with exit code: 1
这可能吗?如果是这样,我做错了什么?
最佳答案
Mathias R. Jessen提供了关键指针:
使用 Azure 是您的问题的偶然,它源于基本的 PowerShell 行为:
与其他语言不同,PowerShell 不执行函数提升,...
...这意味着您必须先声明您的函数然后才能调用它们,即在源代码中您必须将函数定义< em>在任何调用它的语句之前。
相关概念帮助主题,about_Functions不幸的是,历史上并没有明确这一点,但此后已得到纠正。现有 PowerShell 安装的离线帮助需要手动更新才能看到更改。
要为您的代码阐明解决方案:
- task: AzureCLI@2
displayName: "My Task"
inputs:
scriptType: pscore
scriptLocation: inlineScript
inlineScript: |
# First, declare the function.
function Do-Something {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $Hello,
[Parameter(Mandatory=$true, Position=1)]
[string] $World
)
Write-Host "$Hello $World"
}
# Now you can call it.
Do-Something "hello" "world"
Do-Something "goodbye" "world"
关于function - Azure 管道 YAML 文件中的内联 powershell 脚本中是否可以包含函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70018761/