Azure 自动化——如何拆分通用功能

Azure Automation - how to split out common functions

我想知道是否有一种方法可以在 Azure Automation 的单独 runbook 中定义常用函数?例如,我有一个日志记录功能,可以为消息添加时间戳并在出现错误时退出,我在多个运行手册中使用了它。我想定义一次,然后从其他运行手册中调用它。而且以后改的话,只需要改一个地方就可以了。

我知道我可以定义父/子 runbook 并内联调用它们,这让我想知道我是否可以拆分出一个函数定义,然后从另一个 runbook 调用该 runbook 以“导入”该函数到当前的运行手册中。例如,我有一个名为“Test-FunctionDefinition”的运行手册,代码如下:

function Test-FunctionDefintion() {
  param (
    [String] $TestParam
  )
  Write-Output "Output from test function: $TestParam"
}

我希望能够像这样从另一个 runbook 内联调用它来定义函数,然后能够使用该函数:

& .\Test-FunctionDefinition.ps1

Test-FunctionDefinition -TestParam "Test String"

我尝试创建这两个运行手册,但虽然它在第 1 行似乎调用运行手册“Test-FunctionDefiniton”没问题,但随后调用第 3 行的函数失败并显示:

Test-FunctionDefinition : The term 'Test-FunctionDefinition' is not recognized as the name of a cmdlet, function, script file, or operable program.

我想做的事情可行吗?我意识到我可以只修改我的运行手册并调用 & .\Test-FunctionDefinition.ps1 -TestParam "Test String",但如果可能的话我更愿意以其他方式进行。

看起来应该是可以的 - Create modular runbooks in Automation

你有两个选项:

  • 内联 - Child 运行书籍 运行 与 parent.
  • 在同一工作中
  • Cmdlet - 为 child 运行 图书创建了一个单独的作业。

对于 powershell 运行这本书应该很简单

$vm = Get-AzVM -ResourceGroupName "LabRG" -Name "MyVM"
$output = .\PS-ChildRunbook.ps1 -VM $vm -RepeatCount 2 -Restart $true

我做了一些更多的测试以确保我最初的假设(在一个脚本中定义一个函数并在另一个脚本中调用它)如我预期的那样工作,但我得到了同样的错误。看来您需要点源而不是使用 &。这在 PowerShell 控制台和 Azure 自动化中都有效:

. .\Test-FunctionDefinition.ps1

Test-FunctionDefinition -TestParam "Test String"

注意开头的“.”代替 '&'。我需要查看它们之间的区别...