使用 .zip 文件归档部署 PowerShell Lambda 函数 - Amazon Lambda
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

使用 .zip 文件归档部署 PowerShell Lambda 函数

PowerShell 运行时部署程序包包含您的 PowerShell 脚本、PowerShell 脚本所需的 PowerShell 模块,以及托管 PowerShell Core 所需的程序集。

创建 Lambda 函数

要使用 Lambda 开始编写并调用 PowerShell 脚本,您可以使用 New-AWSPowerShellLambda cmdlet 基于模板创建一个入门脚本。您可以使用 Publish-AWSPowerShellLambda cmdlet 将脚本部署到 Lambda。然后,您可以通过命令行或 Lambda 控制台测试您的脚本。

要创建、上传和测试新的 PowerShell 脚本,请执行以下操作:

  1. 要查看可用模板列表,请运行以下命令:

    PS C:\> Get-AWSPowerShellLambdaTemplate Template Description -------- ----------- Basic Bare bones script CodeCommitTrigger Script to process Amazon CodeCommit Triggers ...
  2. 要基于 Basic 模板创建示例脚本,请运行以下命令:

    New-AWSPowerShellLambda -ScriptName MyFirstPSScript -Template Basic

    当前目录的新子目录中创建一个名为 MyFirstPSScript.ps1 的新文件。目录名称基于 -ScriptName 参数。您可以使用 -Directory 参数来选择其他目录。

    您可以看到新文件包含以下内容:

    # PowerShell script file to run as a Lambda function # # When executing in Lambda the following variables are predefined. # $LambdaInput - A PSObject that contains the Lambda function input data. # $LambdaContext - An Amazon.Lambda.Core.ILambdaContext object that contains information about the currently running Lambda environment. # # The last item in the PowerShell pipeline is returned as the result of the Lambda function. # # To include PowerShell modules with your Lambda function, like the AWSPowerShell.NetCore module, add a "#Requires" statement # indicating the module and version. #Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.618.0'} # Uncomment to send the input to CloudWatch Logs # Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5)
  3. 要查看日志消息如何从您的 PowerShell 脚本发送到 Amazon CloudWatch Logs,请取消示例脚本的 Write-Host 行的注释。

    要演示如何从 Lambda 函数返回数据,请使用 $PSVersionTable 在脚本末尾添加新的一行。这会将 $PSVersionTable 添加到 PowerShell 管道。PowerShell 脚本完成后,PowerShell 管道中的最后一个对象是 Lambda 函数的返回数据。$PSVersionTable 是 PowerShell 全局变量,还提供有关正在运行的环境的信息。

    做出这些更改之后,示例脚本的最后两行如下所示:

    Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5) $PSVersionTable
  4. 编辑 MyFirstPSScript.ps1 文件后,将目录更改为脚本的位置。然后运行以下命令,将脚本发布到 Lambda:

    Publish-AWSPowerShellLambda -ScriptPath .\MyFirstPSScript.ps1 -Name MyFirstPSScript -Region us-east-2

    注意,-Name 参数指定 Lambda 函数名称,该名称将显示在 Lambda 控制台中。您可以使用此函数手动调用脚本。

  5. 使用 Amazon Command Line Interface (Amazon CLI) invoke 命令调用您的函数。

    > aws lambda invoke --function-name MyFirstPSScript out