

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 .zip 封存檔部署 PowerShell Lambda 函數
<a name="powershell-package"></a>

PowerShell 執行時間的部署套件包含 PowerShell 指令碼、PowerShell 指令碼所需要的 PowerShell 模組，以及代管 PowerShell Core 所需的組件。

## 建立 Lambda 函數
<a name="powershell-package-create"></a>

若要開始使用 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 AWS CodeCommit Triggers
   ...
   ```

1. 若要根據 `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)
   ```

1. 若要了解日誌訊息如何從 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
   ```

1. 在您編輯 `MyFirstPSScript.ps1` 檔案之後，請將目錄變更為指令碼的位置。然後執行下列命令，將指令碼發佈至 Lambda︰

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

   請注意，`-Name` 參數指定 Lambda 函數名稱，此名稱會出現在 Lambda 主控台。您可以使用此函式來手動叫用您的指令碼。

1. 使用 AWS Command Line Interface (AWS CLI) `invoke` 命令來叫用函數。

   ```
   > aws lambda invoke --function-name MyFirstPSScript out
   ```