

# .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`을 사용해 스크립트 끝에 새 행을 추가합니다. 그러면 PowerShell 파이프라인에 `$PSVersionTable` 테이블이 추가됩니다. 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
   ```