PowerShell codes samples for some of our popular AWS services.
Monitoring
CloudWatch Logs
These code samples assume you have configured AWS Credentials and a default AWS Region. The Using AWS Credentials documentation provides details on how to set these up.
The AWS Tools for PowerShell Reference website holds all cmdlet documentation for the AWSPowerShell and AWSPowerShell.NetCore PowerShell Modules. The examples here use the following cmdlets:
The required IAM Policy for each call is included in the examples, however for more information about Amazon CloudWatch IAM Policy Actions, refer to the Amazon CloudWatch Logs Permissions Reference.
# Uses the "logs:CreateLogGroup" IAM Policy.
New-CWLLogGroup -LogGroupName 'MyLogGroup'
# Uses the "logs:CreateLogStream" IAM Policy.
$splat = @{
LogGroupName = 'MyLogGroup'
LogStreamName = 'MyLogStream'
}
New-CWLLogStream @splat
# Set variables for the Log Group and Log Stream
$logGroupName = 'MyLogGroup'
$logStreamName = 'MyLogStream'
$logEntry = New-Object -TypeName 'Amazon.CloudWatchLogs.Model.InputLogEvent'
$logEntry.Message = 'My first log entry'
$logEntry.Timestamp = (Get-Date).ToUniversalTime()
# Uses the "logs:PutLogEvents" IAM Policy.
$splat = @{
LogEvent = $logEntry
LogGroupName = $logGroupName
LogStreamName = $logStreamName
}
$sequenceToken = Write-CWLLogEvent @splat
# Write a second Log Entry to the same Log Stream, using the SequenceToken
$logEntry = New-Object -TypeName 'Amazon.CloudWatchLogs.Model.InputLogEvent'
$logEntry.Message = 'My second log entry'
$logEntry.Timestamp = (Get-Date).ToUniversalTime()
$splat = @{
LogEvent = $logEntry
LogGroupName = $logGroupName
LogStreamName = $logStreamName
SequenceToken = $sequenceToken
}
$sequenceToken = Write-CWLLogEvent @splat
More information about the PutLogEvents API and the batch event limits can be found in the PutLogEvents API Reference.
$listOfEvents = New-Object -TypeName 'System.Collections.Generic.List[Amazon.CloudWatchLogs.Model.InputLogEvent]'
$logEntry1 = New-Object -TypeName 'Amazon.CloudWatchLogs.Model.InputLogEvent'
$logEntry1.Message = 'Message 1'
$logEntry1.Timestamp = (Get-Date).ToUniversalTime()
$null = $listOfEvents.Add($logEntry1)
$logEntry2 = New-Object -TypeName 'Amazon.CloudWatchLogs.Model.InputLogEvent'
$logEntry2.Message = 'Message 2'
$logEntry2.Timestamp = (Get-Date).ToUniversalTime()
$null = $listOfEvents.Add($logEntry2)
$splat = @{
LogEvent = $listOfEvents
LogGroupName = $logGroupName
LogStreamName = $logStreamName
SequenceToken = $sequenceToken
}
$sequenceToken = Write-CWLLogEvent @splat
More information about the PutLogEvents exceptions can be found in the PutLogEvents API Reference under the "Errors" header. .
# Instead of performing "DescribeLogGroup" and "DescribeLogStream" API calls to ensure
# the objects exist and to find the correct SequenceToken, attempt to write the log
# entry and leverage known exceptions to create any pre-requisites.
$listOfEvents = New-Object -TypeName 'System.Collections.Generic.List[Amazon.CloudWatchLogs.Model.InputLogEvent]'
$logEntry1 = New-Object -TypeName 'Amazon.CloudWatchLogs.Model.InputLogEvent'
$logEntry1.Message = 'A new message 1'
$logEntry1.Timestamp = (Get-Date).ToUniversalTime()
$null = $listOfEvents.Add($logEntry1)
$logEntry2 = New-Object -TypeName 'Amazon.CloudWatchLogs.Model.InputLogEvent'
$logEntry2.Message = 'A new message 2'
$logEntry2.Timestamp = (Get-Date).ToUniversalTime()
$null = $listOfEvents.Add($logEntry2)
$logGroupName = 'MyLogGroup'
$logStreamName = 'MyLogStream'
$splat = @{
LogEvent = $listOfEvents
LogGroupName = $logGroupName
LogStreamName = $logStreamName
ErrorAction = 'Stop'
}
# This could be swapped out with a for loop
while ($true)
{
try
{
if (-not([String]::IsNullOrWhiteSpace($sequenceToken)))
{
$splat.SequenceToken = $sequenceToken
}
# All non-handled exceptions will throw and break out of the while loop
$sequenceToken = Write-CWLLogEvent @splat
break
}
catch
{
# Depending where this call is executed, PowerShell may wrap exceptions
# inside other Runtime exceptions. If it does, a specific catch statement
# for each defined Exception will not always work. Instead we'll use a global
# catch statement and parse the exception message to identify the cause.
if ($_.Exception.Message -like '*The next batch can be sent with sequenceToken:*')
{
# This exception can often be caught with the following catch statements:
# - catch [Amazon.CloudWatchLogs.Model.DataAlreadyAcceptedException]
# - catch [Amazon.CloudWatchLogs.Model.InvalidSequenceTokenException]
# Sample Exception Message:
# - 'The given batch of log events has already been accepted. The next batch can be sent with sequenceToken: 1234567890'
# We are using wildcards in case the exception is wrapped.
$sequenceToken = $_.Exception.Message.Split(':')[-1].Trim().TrimEnd(')')
# The exception may return the string 'null'. If this is the case, the API
# call was made with a SequenceToken when it is not required.
if ($sequenceToken -eq 'null')
{
# Ensure the splat does not include the SequenceToken
if ($splat.SequenceToken)
{
$splat.Remove('SequenceToken')
}
# Remove the SequenceToken variable
Remove-Variable -Name 'sequenceToken'
}
}
elseif ($_.Exception.Message -like '*The specified log group does not exist.*')
{
# This exception can often be caught with the following catch statements:
# - catch [Amazon.CloudWatchLogs.Model.ResourceNotFoundException]
# Sample Exception Message:
# - 'The specified log group does not exist.'
# We are using wildcards in case the exception is wrapped.
New-CWLLogGroup -LogGroupName $logGroupName -ErrorAction 'Stop'
New-CWLLogStream -LogGroupName $logGroupName -LogStreamName $logStreamName -ErrorAction 'Stop'
# A new CloudWatch Log Stream does not require a SequenceToken. Make
# sure we don't use one by removing the splat property and the variable.
if ($splat.SequenceToken)
{
$splat.Remove('SequenceToken')
}
Remove-Variable -Name 'sequenceToken' -ErrorAction 'SilentlyContinue'
}
elseif ($_.Exception.Message -like '*The specified log stream does not exist.*')
{
# This exception can often be caught with the following catch statements:
# - catch [Amazon.CloudWatchLogs.Model.ResourceNotFoundException]
# Sample Exception Message:
# - 'The specified log stream does not exist.'
# We are using wildcards in case the exception is wrapped.
New-CWLLogStream -LogGroupName $logGroupName -LogStreamName $logStreamName -ErrorAction 'Stop'
# A new CloudWatch Log Stream does not require a SequenceToken. Make
# sure we don't use one by removing the splat property and the variable.
if ($splat.SequenceToken)
{
$splat.Remove('SequenceToken')
}
Remove-Variable -Name 'sequenceToken' -ErrorAction 'SilentlyContinue'
}
else
{
# Additional logic can be added to handle other exceptions that may occur
throw
}
}
}
# Uses the "logs:GetLogEvents" IAM Policy.
$splat = @{
LogGroupName = $logGroupName
LogStreamName = $logStreamName
StartTime = (Get-Date).AddMinutes(-3)
}
$logEvents = Get-CWLLogEvent @splat
foreach ($logEvent in $logEvents.Events)
{
# Perform some work
}
# To continue searching, use the $logEvents.NextBackwardToken or $logEvents.NextForwardToken
$logEvents = Get-CWLLogEvent @splat -NextToken $logEvents.NextBackwardToken
$logEvents = Get-CWLLogEvent @splat -NextToken $logEvents.NextForwardToken
$splat = @{
LogGroupName = $logGroupName
LogStreamName = $logStreamName
StartTime = (Get-Date).AddMinutes(-15)
EndTime = (Get-Date).AddMinutes(-10)
}
$logEvents = Get-CWLLogEvent @splat
foreach ($logEvent in $logEvents.Events)
{
# Perform some work
}
# Uses the "logs:DeleteLogStream" IAM Policy.
Remove-CWLLogStream -LogGroupName 'MyLogGroup' -LogStreamName 'MyLogStream' -Force
# Uses the "logs:DeleteLogGroup" IAM Policy.
Remove-CWLLogGroup -LogGroupName 'MyLogGroup' -Force
Communications
-
Amazon SQS
-
Amazon SNS
-
Amazon SQS
-
Simple Queue Service
These code samples assume you have configured AWS Credentials and a default AWS Region. The Using AWS Credentials documentation provides details on how to set these up.
The AWS Tools for PowerShell Reference website holds all cmdlet documentation for the AWSPowerShell and AWSPowerShell.NetCore PowerShell Modules. The examples here use the following cmdlets:
To identify the IAM Policy Actions required for each API call, refer to the Amazon SQS API Permissions: Actions and Resource Reference.
Code Sample: Create an Amazon SQS Queue# Create an Amazon SQS Queue and return the Amazon SQS Queue Url # Uses the "sqs:CreateQueue" IAM Policy. $splat = @{ QueueName = 'MySQSQueue' Attribute = @{ VisibilityTimeout = '30' ReceiveMessageWaitTimeSeconds = '20' } } $queueUrl = New-SQSQueue @splat
Code Sample: Retrieve an Amazon SQS Queue URL given an Amazon SQS Queue Name# Retrieve an Amazon SQS Queue Url # Uses the "sqs:GetQueueUrl" IAM Policy. $queueUrl = Get-SQSQueueUrl -QueueName 'MySQSQueue'
Code Sample: Retrieve all Amazon SQS Queue Attributes# Uses the "sqs:GetQueueAttributes" IAM Policy. $attributes = Get-SQSQueueAttribute -QueueUrl $queueUrl -AttributeName 'All'
Code Sample: Allow another AWS Account access to send messages to your Amazon SQS Queue# Allow the AWS Account Id referenced to perform "sqs:SendMessage" API calls against an Amazon SQS Queue. # Uses the "sqs:AddPermission" IAM Policy. $awsAccountId = '123456789012' $splat = @{ QueueUrl = $queueUrl Action = 'SendMessage' AWSAccountId = $awsAccountId Label = "AllowSendMessage_$awsAccountId" } Add-SQSPermission @splat
Code Sample: Remove another AWS Account's access from sending messages to your Amazon SQS Queue# Prevents the AWS Account Id referenced from performing "sqs:SendMessage" API calls against an Amazon SQS Queue. # Uses the "sqs:RemovePermission" IAM Policy. $awsAccountId = '123456789012' $splat = @{ QueueUrl = $queueUrl Label = "AllowSendMessage_$awsAccountId" Force = $true } Remove-SQSPermission @splat
Set an SQS Queue Policy# Retrieve the SQS Queue Arn # Uses the "sqs:GetQueueAttributes" IAM Policy $queueArn = (Get-SQSQueueAttribute -QueueUrl $queueUrl -AttributeName 'QueueArn').QueueArn # Create a new SQS Policy. This example allows an SNS Topic to send messages # to the SQS Queue. # Uses the "sqs:SetQueueAttributes" IAM Policy $policy = @" { "Version": "2008-10-17", "Statement": [ { "Sid": "1", "Effect": "Allow", "Principal": "*", "Action": "SQS:SendMessage", "Resource": "$queueArn", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-west-2:902800236179:MySNSTopic" } } } ] } "@ Set-SQSQueueAttribute -QueueUrl $sqsQueueUrl -Attribute @{ Policy = $policy }
Code Sample: Send an Amazon SQS Message or a Message Batch# Send a single Amazon SQS Message # Uses the "sqs:SendMessage" IAM Policy. $splat = @{ QueueUrl = $queueUrl MessageBody = 'YOUR_QUEUE_MESSAGE' } $response = Send-SQSMessage @splat # Send a batch of Amazon SQS Messages # Uses the "sqs:SendMessage" IAM Policy. # Step 1: Create a list of messages to send # New-Object syntax will work in PowerShell v2.0 and up $messages = New-Object -TypeName 'System.Collections.Generic.List[Amazon.SQS.Model.SendMessageBatchRequestEntry]' $messages.Add((New-Object -TypeName 'Amazon.SQS.Model.SendMessageBatchRequestEntry' -ArgumentList 'message1', 'Message1Content')) $messages.Add((New-Object -TypeName 'Amazon.SQS.Model.SendMessageBatchRequestEntry' -ArgumentList 'message2', 'Message2Content')) $messages.Add((New-Object -TypeName 'Amazon.SQS.Model.SendMessageBatchRequestEntry' -ArgumentList 'message3', 'Message3Content')) # From PowerShell v5.0 onwards, you can use this syntax if you prefer $messages = [System.Collections.Generic.List[Amazon.SQS.Model.SendMessageBatchRequestEntry]]::new() $messages.Add(( [Amazon.SQS.Model.SendMessageBatchRequestEntry]::new('message1', 'Message1Content') )) $messages.Add(( [Amazon.SQS.Model.SendMessageBatchRequestEntry]::new('message2', 'Message2Content') )) $messages.Add(( [Amazon.SQS.Model.SendMessageBatchRequestEntry]::new('message3', 'Message3Content') )) # Create a Hashtable for splatting and send the messages $splat = @{ QueueUrl = $queueUrl Entry = $messages } $response = Send-SQSMessageBatch @splat # Print the messages that sent successfully $response.Successful | Format-Table # Print the messages that failed to send $response.Failed | Format-Table
Code Sample: Send an Amazon SQS Message with Message AttributesMore information about the Amazon.SQS.Model.MessageAttributeValue object can be found in the NET Developer documentation.
# Create a MessageAttributes object (syntax for PowerShell v2.0 and up) $attribute1 = New-Object -TypeName Amazon.SQS.Model.MessageAttributeValue $attribute1.DataType = 'String' $attribute1.StringValue = 'MyAttributeValue' # From PowerShell v5.0 onwards, you can use this syntax if you prefer $attribute2 = [Amazon.SQS.Model.MessageAttributeValue]::new() $attribute2.DataType = 'String' $attribute2.StringValue = 'Another Value' # Create a Hashtable to hold the MessageAttribute objects # The Hashtable Key is a [String], the Value is a MessageAttributeValue object $messageAttributes = [System.Collections.Hashtable]::new() $messageAttributes.Add('Attribute_1', $attribute1) $messageAttributes.Add('Another-attribute', $attribute2) # Add the MessageAttribute parameter to the Send-SQSMessage cmdlet # Send a single Amazon SQS Message # Uses the "sqs:SendMessage" IAM Policy. $splat = @{ QueueUrl = $queueUrl MessageBody = 'YOUR_QUEUE_MESSAGE' MessageAttribute = $messageAttributes } $response = Send-SQSMessage @splat
Code Sample: Receive, process and delete messages from an Amazon SQS Queue# Create a Hashtable for splatting against Receive-SQSMessage # This example will receive up to 10 SQS Messages $receiveSQSMessageSplat = @{ QueueUrl = $queueUrl MessageCount = 10 } # Create a Hashtable for splatting against Remove-SQSMessage $removeSQSMessageSplat = @{ QueueUrl = $queueUrl Force = $true } # The following code can be placed in a "while ($true)" loop to continuously process an Amazon SQS Queue # Receive a set of Amazon SQS Messages. # Uses the "sqs:ReceiveMessage" IAM Policy. $sqsMessages = Receive-SQSMessage @receiveSQSMessageSplat foreach ($sqsMessage in $sqsMessages) { # Process the message $sqsMessage.Body # Delete the message when processing succeeded. # Uses the "sqs:DeleteMessage" IAM Policy. Remove-SQSMessage -ReceiptHandle $sqsMessage.ReceiptHandle @removeSQSMessageSplat }
Code Sample: Remove an Amazon SQS Queue# Deletes an Amazon SQS Queue # Uses the "sqs:DeleteQueue" IAM Policy. Remove-SQSQueue -QueueUrl $queueUrl -Force
-
Amazon SNS
-
Simple Notification Service
These code samples assume you have configured AWS Credentials and a default AWS Region. The Using AWS Credentials documentation provides details on how to set these up.
The AWS Tools for PowerShell Reference website holds all cmdlet documentation for the AWSPowerShell and AWSPowerShell.NetCore PowerShell Modules. The examples here use the following cmdlets:
Code Sample: Create an Amazon SNS Topic# Uses the "SNS:CreateTopic" IAM Policy $snsTopicArn = New-SNSTopic -Name 'MySNSTopic'
Code Sample: List Amazon SNS Topics and their attributes# Uses the "SNS:ListTopics" IAM Policy $snsTopics = Get-SNSTopic $snsTopics foreach ($topicArn in $snsTopics.TopicArn) { # Uses the "SNS:ListSubscriptionsByTopic" IAM Policy Get-SNSSubscriptionByTopic -TopicArn $topicArn # Uses the "SNS:GetTopicAttributes" IAM Policy Get-SNSTopicAttribute -TopicArn $topicArn }
Code Sample: Subscribe an email address to an SNS Topic# Uses the "SNS:Subscribe" IAM Policy $connectSNSNotificationSplat = @{ TopicArn = $snsTopicArn Protocol = 'email' Endpoint = 'sample@example.com' } Connect-SNSNotification @connectSNSNotificationSplat
Code Sample: Subscribe an Amazon SQS Queue to an Amazon SNS TopicMore information can be found in the Sending Messages to Amazon SQS Queues documentation.
# Create an Amazon SQS Queue # Uses the "sqs:CreateQueue" IAM Policy $sqsQueueUrl = New-SQSQueue -QueueName 'MySQSQueue' # Retrieve the SQS Queue Arn # Uses the "sqs:GetQueueAttributes" IAM Policy $sqsQueueArn = (Get-SQSQueueAttribute -QueueUrl $sqsQueueUrl -AttributeName 'QueueArn').QueueArn # Grant the SNS Topic permission to send messages to the SQS Queue # Uses the "sqs:SetQueueAttributes" IAM Policy $policy = @" { "Version": "2008-10-17", "Statement": [ { "Sid": "1", "Effect": "Allow", "Principal": "*", "Action": "SQS:SendMessage", "Resource": "$sqsQueueArn", "Condition": { "ArnEquals": { "aws:SourceArn": "$snsTopicArn" } } } ] } "@ Set-SQSQueueAttribute -QueueUrl $sqsQueueUrl -Attribute @{ Policy = $policy } # Subscribe the SQS Queue to the SNS Topic # Uses the "SNS:Subscribe" IAM Policy $connectSQSQueueSplat = @{ TopicArn = $snsTopicArn Protocol = 'sqs' Endpoint = $sqsQueueArn } Connect-SNSNotification @connectSQSQueueSplat
Code Sample: Publish a message to an Amazon SNS Topic# Uses the "SNS:Publish" IAM Policy $publishSNSMessageSplat = @{ Message = 'Testing 1234' Subject = 'Test' TopicArn = $snsTopicArn } Publish-SNSMessage @publishSNSMessageSplat
Code Sample: Delete an Amazon SNS Topic# Uses the "SNS:DeleteTopic" IAM Policy Remove-SNSTopic -TopicArn $snsTopicArn -Force
Serverless
-
AWS Lambda
-
Step Functions
-
AWS Lambda
-
Lambda
These code samples assume you have configured AWS Credentials and a default AWS Region. The Using AWS Credentials documentation provides details on how to set these up.
The AWS Tools for PowerShell Reference website holds all cmdlet documentation for the AWSPowerShell and AWSPowerShell.NetCore PowerShell Modules. The examples here use the following cmdlets:
Update-LMFunctionConfiguration
More Information about AWS Lambda IAM Policies can be found on the Lambda API Permissions Reference page.
These examples assume you have already packaged and created a zip file of your AWS Lambda Function code. You have either published the zip file to an S3 Bucket, or you have a path to the file on your local disk. The examples are based off the .NET Core 2.1 Runtime, but are easily modified for other AWS Lambda Runtimes.
Code Sample: Create an AWS Lambda Function$lambdaFunctionName = 'HelloWorld' # Set variables for either S3 Bucket/Key or local file path $s3BucketName = 'MyS3BucketName' $s3Key = 'path/to/code.zip' $zipFilePath = 'C:\Path\To\code.zip' # Create an IAM Policy # Uses the "iam:CreatePolicy" IAM Policy # Note this is the minimum viable policy to allow CloudWatch logging $policyDocument = '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" } ] }' $splat = @{ PolicyName = $lambdaFunctionName Description = "IAM Policy for the $lambdaFunctionName Lambda Function" PolicyDocument = $policyDocument } $iamPolicy = New-IAMPolicy @splat # Create an IAM Role # Used the "iam:CreateRole" IAM Policy $assumeRolePolicyDocument = '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }' $splat = @{ RoleName = $lambdaFunctionName Description = "IAM Role for the $lambdaFunctionName Lambda Function" AssumeRolePolicyDocument = $assumeRolePolicyDocument } $iamRole = New-IAMRole @splat # Associate the IAM Policy with the IAM Role # Uses the "iam:AttachRolePolicy" IAM Policy $splat = @{ RoleName = $lambdaFunctionName PolicyArn = $iamPolicy.Arn } Register-IAMRolePolicy @splat # Example splat to create a LambdaFunction from a zip file in S3 $lmSplat = @{ FunctionName = $lambdaFunctionName Description = 'My HelloWorld .NET Lambda Function' BucketName = $s3BucketName Key = $s3Key Role = $iamRole.Arn Handler = 'DLLName::NameSpace.Class::Method' Runtime = 'dotnetcore2.1' MemorySize = 256 Timeout = 60 Environment_Variable = @{ AnEnvironmentVariableName = 'Value' } Publish = $true } # Example splat to create a LambdaFunction from a local zip file $lmSplat = @{ FunctionName = $lambdaFunctionName Description = 'My HelloWorld .NET Lambda Function' ZipFilename = $zipFilePath Role = $iamRole.Arn Handler = 'DLLName::NameSpace.Class::Method' Runtime = 'dotnetcore2.1' MemorySize = 256 Timeout = 60 Environment_Variable = @{ AnEnvironmentVariableName = 'Value' } Publish = $true } # If publishing the Lambda Function too soon after the IAM Role is created, # the cmdlet will throw an exception because the IAM Role is not yet available. while ($true) { try { # Uses the "lambda:CreateFunction" IAM Policy $null = Publish-LMFunction @lmSplat break } catch { if ($_.Exception.Message -like '*The role defined for the function cannot be assumed by Lambda*') { Write-Verbose -Message 'Sleeping 2 seconds to allow the IAM Role to propagate' -Verbose Start-Sleep -Seconds 5 } else { throw } } }
Code Sample: Update an AWS Lambda Function's Code# Uses the "lambda:UpdateFunctionCode" IAM Policy # From a zip file in S3 $splat = @{ FunctionName = 'HelloWorld' BucketName = 'MyS3BucketName' Key = 'path/to/code.zip' Publish = $true Force = $true } # From a local zip file $splat = @{ FunctionName = 'HelloWorld' ZipFilename = 'C:\PathToCode.zip' Publish = $true Force = $true } Update-LMFunctionCode @splat
Code Sample: Overwrite an AWS Lambda Functions Environment VariablesThis example is easily modified to change any other configuration of an AWS Lambda Function.# Warning: this will *overwrite* existing Environment Variables # Uses the "lambda:UpdateFunctionConfiguration" Iam Policy $splat = @{ FunctionName = 'HelloWorld' Environment_Variable = @{ AnEnvironmentVariableName = 'Value' } } Update-LMFunctionConfiguration @splat
Code Sample: Invoke an AWS Lambda Function# Uses the "lambda:InvokeFunction" IAM Policy $payload = ConvertTo-Json -Compress -InputObject @{ foo = 'bar' } $response = Invoke-LMFunction -FunctionName 'HelloWorld' -Payload $payload # Read the response payload $reader = New-Object -TypeName 'System.IO.StreamReader' -ArgumentList $response.Payload $reader.ReadToEnd()
-
Step Functions
-
Step Functions
These code samples assume you have configured AWS Credentials and a default AWS Region. The Using AWS Credentials documentation provides details on how to set these up.
The AWS Tools for PowerShell Reference website holds all cmdlet documentation for the AWSPowerShell and AWSPowerShell.NetCore PowerShell Modules. The examples here use the following cmdlets:
The examples on this page can be followed top to bottom, variables are re-used between examples.
Code Sample: Create an Activity Task# Uses the "states:CreateActivity" IAM Policy. $activityTask = New-SFNActivity -Name 'HelloWorld'
Code Sample: Create an AWS Step Functions State MachineThis example leverages an Activity Task instead of a Lambda Function.# Create an IAM Role for the State Machine's execution Role # Set a name for the State Machine $stateMachineName = 'HelloWorldStateMachine' # Get the default AWS Region from the Shell, or set one. # This is required to allow the State Machine service to assume # your IAM Role to execute your State Machine. $region = (Get-DefaultAWSRegion).Region $region = 'us-east-1' # Create an IAM Policy # Uses the "iam:CreatePolicy" IAM Policy # Note this is the standard "service role default" that would be created # if using the AWS Console $policyDocument = ConvertTo-Json -Compress -Depth 4 -InputObject @{ Version = '2012-10-17' Statement = @( @{ Effect = 'Allow' Action = 'lambda:InvokeFunction' Resource = '*' } ) } $splat = @{ PolicyName = 'StatesExecutionPolicy-{0}' -f $stateMachineName Description = "IAM Policy for the $stateMachineName execution role" PolicyDocument = $policyDocument } $iamPolicy = New-IAMPolicy @splat # Create an IAM Role # Used the "iam:CreateRole" IAM Policy $assumeRolePolicyDocument = ConvertTo-Json -Compress -Depth 4 -InputObject @{ Version = '2012-10-17' Statement = @( @{ Effect = 'Allow' Principal = @{ Service = "states.$region.amazonaws.com" } Action = 'sts:AssumeRole' } ) } $splat = @{ RoleName = 'StatesExecutionRole-{0}' -f $stateMachineName Description = "IAM Role for the $stateMachineName State Machine execution role" AssumeRolePolicyDocument = $assumeRolePolicyDocument } $iamRole = New-IAMRole @splat # Associate the IAM Policy with the IAM Role # Uses the "iam:AttachRolePolicy" IAM Policy $splat = @{ RoleName = 'StatesExecutionRole-{0}' -f $stateMachineName PolicyArn = $iamPolicy.Arn } Register-IAMRolePolicy @splat # Create a State Machine using our Activity Task and the SFN service-role # Uses the "states:CreateStateMachine" IAM Policy $json = ConvertTo-Json -Compress -InputObject @{ Comment = 'Hello World Activity Task Example' StartAt = 'HelloWorld' States = @{ HelloWorld = @{ Type = 'Task' Resource = $activityTask.ActivityArn End = $true } } } $newSFNStateMachineSplat = @{ Name = $stateMachineName RoleArn = $iamRole.Arn Definition = $json } $stateMachine = New-SFNStateMachine @newSFNStateMachineSplat
Code Sample: Invoke a State Machine# Uses the "states:StartExecution" IAM Policy # Create a json string for input $json = ConvertTo-Json -Compress -InputObject @{ foo = 'bar' } $startSFNExecutionSplat = @{ Input = $json StateMachineArn = $stateMachine.StateMachineArn } $execution = Start-SFNExecution @startSFNExecutionSplat
Code Sample: Process an Activity Task# IAM Policies required: # - "states:GetActivityTask" # - "states:SendTaskFailure" # - "states:SendTaskHeartbeat" # - "states:SendTaskSuccess" while ($true) { $getSFNActivityTaskSplat = @{ ActivityArn = $activityTask.ActivityArn WorkerName = 'MyWorker' } $task = Get-SFNActivityTask @getSFNActivityTaskSplat if (-not([String]::IsNullOrWhiteSpace($task.TaskToken))) { # Process the task # How to send a Task Heartbeat Send-SFNTaskHeartbeat -TaskToken $task.TaskToken # How to send a Task Success # Craft a json response $success = ConvertTo-Json -Compress -InputObject @{ message = 'success' } Send-SFNTaskSuccess -Output $success -TaskToken $task.TaskToken # How to send a Task Failure $failureSplat = @{ Error = 'FailureException' Cause = 'Something went wrong' TaskToken = $task.TaskToken } Send-SFNTaskFailure @failureSplat } }
Code Sample: Get the list of a State Machines Executions# Uses the "states:ListExecutions" IAM Policy $executionList = Get-SFNExecutionList -StateMachineArn $stateMachine.StateMachineArn $executionList
Code Sample: Get the status of a State Machine Execution# Uses the "states:DescribeExecution" IAM Policy $status = Get-SFNExecution -ExecutionArn $execution.ExecutionArn $status
Code Sample: Get the history of a State Machine Execution# Uses the "states:GetExecutionHistory" IAM Policy $history = Get-SFNExecutionHistory -ExecutionArn $execution.ExecutionArn $history
Code Sample: Delete an AWS Step Functions State Machine# Uses the "states:DeleteStateMachine" IAM Policy # This will fail if there are any executions in "Running" state $splat = @{ StateMachineArn = $stateMachine.StateMachineArn Force = $true } Remove-SFNStateMachine @splat
Code Sample: Delete an AWS Step Functions Activity Task# Uses the "states:DeleteActivity" IAM Policy $splat = @{ ActivityArn = $activityTask.ActivityArn Force = $true } Remove-SFNActivity @splat
Code Sample: Remove an IAM Role and IAM Policy# Uses the "iam:DetachRolePolicy" IAM Policy $splat = @{ RoleName = 'StatesExecutionRole-{0}' -f $stateMachineName PolicyArn = $iamPolicy.Arn Force = $true } Unregister-IAMRolePolicy @splat # Uses the "iam:DeleteRole" IAM Policy $splat = @{ RoleName = 'StatesExecutionRole-{0}' -f $stateMachineName Force = $true } Remove-IAMRole @splat # Uses the "iam:DeletePolicy" IAM Policy $splat = @{ PolicyArn = $iamPolicy.Arn Force = $true } Remove-IAMPolicy @splat
Storage
-
Amazon DynamoDB
-
Amazon DynamoDB
-
DynamoDB
These code samples assume you have configured AWS Credentials and a default AWS Region. The Using AWS Credentials documentation provides details on how to set these up.
The AWS Tools for PowerShell Reference website holds all cmdlet documentation for the AWSPowerShell and AWSPowerShell.NetCore PowerShell Modules. The AWS SDK for .NET Version 3 API Reference holds all .NET API documentation for the AWS SDK for .NET. The examples here use a mix of PowerShell cmdlets and the AWS .NET SDK to perform actions against a DynamoDB Table.
The examples here use the following cmdlets:
The examples here use the following AWS SDK for .NET Namespaces:
Amazon.DynamoDBv2.AmazonDynamoDBClient
Amazon.DynamoDBv2.DocumentModel.Document
Amazon.DynamoDBv2.DocumentModel.Expression
Amazon.DynamoDBv2.DocumentModel.PutItemOperationConfig
Amazon.DynamoDBv2.DocumentModel.Primitive
Amazon.DynamoDBv2.DocumentModel.QueryFilter
Amazon.DynamoDBv2.DocumentModel.QueryOperator
Amazon.DynamoDBv2.DocumentModel.Table
Amazon.DynamoDBv2.DocumentModel.UpdateItemOperationConfig
To identify the IAM Policy Actions required for each API call, refer to the DynamoDB API Permissions: Actions, Resources, and Conditions Reference.
Code Sample: Create an Amazon DynamoDB TableUse PowerShell Cmdlets to create a DynamoDB Table.# Uses the "dynamodb:CreateTable" IAM Policy. # Create a Table with a Hash Key only $tableName1 = 'MyTableWithHashKey' $schema1 = New-DDBTableSchema $schema1 | Add-DDBKeySchema -KeyName 'id' -KeyDataType 'S' $schema1 | New-DDBTable -TableName $tableName1 -ReadCapacity 5 -WriteCapacity 5 # Create a Table with Hash and Range Keys $tableName2 = 'MyTableWithRangeKey' $schema2 = New-DDBTableSchema $schema2 | Add-DDBKeySchema -KeyName 'id' -KeyDataType 'S' -KeyType 'HASH' $schema2 | Add-DDBKeySchema -KeyName 'range' -KeyDataType 'S' -KeyType 'RANGE' $schema2 | New-DDBTable -TableName $tableName2 -ReadCapacity 5 -WriteCapacity 5
Code Sample: Create a .NET Table object for interacting with an Amazon DynamoDB TableTo support the CRUD operations from PowerShell, we will use the AWS .NET SDK and the DynamoDB Document Model. In this section we will create the required clients for interacting with a DynamoDB Table
# Create an Amazon DynamoDB Document Model Table Object # To create this client, we likely need an AWS Credential and AWS RegionEndpoint object # You may be able to use default credentials, however in this exampe we will create a # credential object to use. $awsCredential = Get-AWSCredential -ProfileName profilename # Create a RegionEndpoint object directly, or using an AWS Region name $region = [Amazon.RegionEndpoint]::USWest2 $region = [Amazon.RegionEndpoint]::GetBySystemName('us-west-2') # Create an AmazonDynamoDBClient. This is used for the underlying API calls # - Use default AWS credentials, or an AWS credential object $client = New-Object -TypeName Amazon.DynamoDBv2.AmazonDynamoDBClient -ArgumentList $region $client = New-Object -TypeName Amazon.DynamoDBv2.AmazonDynamoDBClient -ArgumentList $awsCredential, $region # Create a Table object. This is used for calls using the DynamoDB Document Model $table = [Amazon.DynamoDBv2.DocumentModel.Table]::LoadTable($client, $tableName)
Code Sample: Put an item in an Amazon DynamoDB TableThis example demonstrates performing a PutItem request against a DynamoDB Table that only has a Hash Key.# Uses the "dynamodb:PutItem" IAM Policy. # Create a Document object from a json string. $json = ConvertTo-Json -Compress -InputObject @{ id = 'MyHashKeyValue' property = 'My Value' type = 'TestObject' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Perform the PutItem operation. Note the PowerShell Core request is asynchronous. if ($PSEdition -eq 'Core') { # PowerShell Core $table.PutItemAsync($document).Wait() } else { # Windows PowerShell $table.PutItem($document) }
This example demonstrates performing a PutItem request with a conditional statement against a DynamoDB Table that only has a Hash Key. For more information about formatting conditional statements, refer to the "Code Sample: Expression Statements" section below.# Uses the "dynamodb:PutItem" IAM Policy. # Create a Document object from a json string. $key = 'id' $value = 'MyHashKeyValue' $json = ConvertTo-Json -Compress -InputObject @{ $key = $value property = 'My Value' type = 'TestObject' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Create a DocumentModel Expression $expression = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Expression # Example ExpressionStatement for attribute_not_exists $expression.ExpressionStatement = "attribute_not_exists ($key)" # Example ExpressionStatement for does not equal $expression.ExpressionStatement = "$key <> :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value $putItemConfiguration = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.PutItemOperationConfig $putItemConfiguration.ConditionalExpression = $expression # Perform the PutItem operation. Note the PowerShell Core request is asynchronous. if ($PSEdition -eq 'Core') { # PowerShell Core $table.PutItemAsync($document, $putItemConfiguration).Wait() } else { # Windows PowerShell $table.PutItem($document, $putItemConfiguration) }
This example demonstrates performing a PutItem request against a DynamoDB Table that has a Hash and Range Key.# Uses the "dynamodb:PutItem" IAM Policy. # Create a Document object from a json string. # This example uses a Range key called "range", and sets it to a # string value of the number of seconds since epoch. $epoch = [DateTimeOffset]::Now.ToUnixTimeSeconds() $json = ConvertTo-Json -Compress -InputObject @{ id = 'MyHashKeyValue' range = $epoch.ToString() property = 'My Value' type = 'TestObject' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Perform the PutItem operation. Note the PowerShell Core request is asynchronous. if ($PSEdition -eq 'Core') { # PowerShell Core $table.PutItemAsync($document).Wait() } else { # Windows PowerShell $table.PutItem($document) }
Code Sample: Update an item in an Amazon DynamoDB TableThis example demonstrates performing an UpdateItem request against a DynamoDB Table that only has a Hash Key.# Uses the "dynamodb:UpdateItem" IAM Policy. # Create a Document object from a json string. $json = ConvertTo-Json -Compress -InputObject @{ id = 'MyHashKeyValue' property = 'My New Value' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Perform the UpdateItem operation. Note the PowerShell Core request is asynchronous. if ($PSEdition -eq 'Core') { # PowerShell Core $table.UpdateItemAsync($document).Wait() } else { # Windows PowerShell $table.UpdateItem($document) }
This example demonstrates performing an UpdateItem request with a conditional statement against a DynamoDB Table that only has a Hash Key. For more informaiton about formatting conditional statements, refer to the "Code Sample: Expression Statements" section below.# Uses the "dynamodb:UpdateItem" IAM Policy. # Create a Document object from a json string. $key = 'id' $value = 'MyHashKeyValue' $json = ConvertTo-Json -Compress -InputObject @{ $key = $value property = 'My New Value' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Create a DocumentModel Expression $expression = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Expression # Example ExpressionStatement for attribute_not_exists $expression.ExpressionStatement = "attribute_not_exists ($key)" # Example ExpressionStatement for does not equal $expression.ExpressionStatement = "$key <> :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value $updateItemConfiguration = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.UpdateItemOperationConfig $updateItemConfiguration.ConditionalExpression = $expression # Perform the UpdateItem operation. Note the PowerShell Core request is asynchronous. if ($PSEdition -eq 'Core') { # PowerShell Core $table.UpdateItemAsync($document, $updateItemConfiguration).Wait() } else { # Windows PowerShell $table.UpdateItem($document, $updateItemConfiguration) }
This example demonstrates performing an UpdateItem request against a DynamoDB Table that has a Hash and Range Key.# Uses the "dynamodb:UpdateItem" IAM Policy. # Create a Document object from a json string. $epoch = [DateTimeOffset]::Now.ToUnixTimeSeconds() $json = ConvertTo-Json -Compress -InputObject @{ id = 'MyHashKeyValue' range = $epoch.ToString() property = 'My New Value' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Perform the UpdateItem operation. Note the PowerShell Core request is asynchronous. if ($PSEdition -eq 'Core') { # PowerShell Core $table.UpdateItemAsync($document).Wait() } else { # Windows PowerShell $table.UpdateItem($document) }
Code Sample: Get an item from an Amazon DynamoDB TableThis example demonstrates performing a GetItem request against a DynamoDB Table that only has a Hash Key.# Uses the "dynamodb:GetItem" IAM Policy. # Create the Hash Key Primitive $hashKey = [Amazon.DynamoDBv2.DocumentModel.Primitive]::new('MyHashKeyValue') # Returns a Amazon.DynamoDBv2.DocumentModel.Document object if ($PSEdition -eq 'Core') { # PowerShell Core $result = $table.GetItemAsync($hashKey).Result } else { # Windows PowerShell $result = $table.GetItem($hashKey) } # Print the output as Json $result.ToJson() $result.ToJsonPretty() # Access the DynamoDB properties like a hashtable $result['property'] $result['property'].Value # Get a PowerShell Object from the response object $item = ConvertFrom-Json -InputObject $result.ToJson() $item
This example demonstrates using a JSON object to perform a GetItem request against a DynamoDB Table that only has a Hash Key.# Uses the "dynamodb:GetItem" IAM Policy. # Create the Hash Key Primitive $json = ConvertTo-Json -Compress -InputObject @{ HashKey = 'HashKeyValue' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Returns a Amazon.DynamoDBv2.DocumentModel.Document object if ($PSEdition -eq 'Core') { # PowerShell Core $result = $table.GetItemAsync($document).Result } else { # Windows PowerShell $result = $table.GetItem($document) } # Print the output as Json $result.ToJson() $result.ToJsonPretty() # Access the DynamoDB properties like a hashtable $result['property'] $result['property'].Value # Get a PowerShell Object from the response object $item = ConvertFrom-Json -InputObject $result.ToJson() $item
This example demonstrates performing a GetItem request against a DynamoDB Table that has a Hash and Range Key.# Uses the "dynamodb:GetItem" IAM Policy. # Create the Hash and Range Key Primitives $hashKey = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Primitive -ArgumentList 'MyHashKeyValue' $rangeKey = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Primitive -ArgumentList $epoch.ToString() # Returns a Amazon.DynamoDBv2.DocumentModel.Document object if ($PSEdition -eq 'Core') { # PowerShell Core $result = $table.GetItemAsync($hashKey,$rangeKey).Result } else { # Windows PowerShell $result = $table.GetItem($hashKey, $rangeKey) } # Print the output as Json $result.ToJson() $result.ToJsonPretty() # Access the DynamoDB properties like a hashtable $result['property'] $result['property'].Value # Get a PowerShell Object from the response object $item = ConvertFrom-Json -InputObject $result.ToJson() $item
Code Sample: Query an Amazon DynamoDB TableThis example demonstrates performing a Query against a DynamoDB Table that only has a Hash Key.# Uses the "dynamodb:Query" IAM Policy. # Create the Query Operator and Query Filter objects. $operator = [Amazon.DynamoDBv2.DocumentModel.QueryOperator]::Equal $filter = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.QueryFilter -ArgumentList 'id', $operator, 'MyHashKeyValue' # Create the Query object $search = $table.Query($filter) # Create the List for storing the retrieved Document objects $documentList = New-Object -TypeName 'System.Collections.Generic.List[Amazon.DynamoDBv2.DocumentModel.Document]' # To ensure errors are terminating and we don't get stuck in a loop, use ErrorActionPreference $eap = $ErrorActionPreference $ErrorActionPreference = 'Stop' try { do { if ($PSEdition -eq 'Core') { # PowerShell Core $documentSet = $search.GetNextSetAsync().Result } else { # Windows PowerShell $documentSet = $search.GetNextSet() } # Process the Document objects retrieves in this API call foreach ($document in $documentSet) { # Perform work against each document here, or # save each document to an array for processing later $null = $documentList.Add($document) } } while (-not $search.IsDone) } catch { # Take action on exception } finally { $ErrorActionPreference = $eap }
This example demonstrates performing a Query against a DynamoDB Table that using both a Hash and Range Key.# Uses the "dynamodb:Query" IAM Policy. # This example will query for a range key greater than the seconds since Epoch from 50 days ago $hashKey = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Primitive -ArgumentList 'MyHashKeyValue' # Calculate the seconds since epoch value for our starting timestamp $startTime = [datetime][DateTimeOffset]::Now.ToUnixTimeSeconds() $twoWeeksAgo = [datetime]::UtcNow.AddDays(-50) $twoWeeksAgoEpoch = (New-TimeSpan -Start $startTime -End $twoWeeksAgo).TotalSeconds.ToString() # Create the Query Operator and Query Filter objects. $operator = [Amazon.DynamoDBv2.DocumentModel.QueryOperator]::GreaterThan $filter = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.QueryFilter -ArgumentList 'range', $operator, $twoWeeksAgoEpoch # Create the Query object $search = $table2.Query($hashKey, $filter) # Create the List for storing the retrieved Document objects $documentList = New-Object -TypeName 'System.Collections.Generic.List[Amazon.DynamoDBv2.DocumentModel.Document]' # To ensure errors are terminating and we don't get stuck in a loop, use ErrorActionPreference $eap = $ErrorActionPreference $ErrorActionPreference = 'Stop' try { do { if ($PSEdition -eq 'Core') { # PowerShell Core $documentSet = $search.GetNextSetAsync().Result } else { # Windows PowerShell $documentSet = $search.GetNextSet() } # Process the Document objects retrieves in this API call foreach ($document in $documentSet) { # Perform work against each document here, or # save each document to an array for processing later $null = $documentList.Add($document) } } while (-not $search.IsDone) } catch { # Take action on exception } finally { $ErrorActionPreference = $eap }
Code Sample: Scan an Amazon DynamoDB Table# Uses the "dynamodb:Scan" IAM Policy. # Create the List for storing the retrieved Document objects $documentList = New-Object -TypeName 'System.Collections.Generic.List[Amazon.DynamoDBv2.DocumentModel.Document]' # To ensure errors are terminating and we don't get stuck in a loop, use ErrorActionPreference $eap = $ErrorActionPreference $ErrorActionPreference = 'Stop' try { $search = $table.Scan($filter) do { if ($PSEdition -eq 'Core') { # PowerShell Core $documentSet = $search.GetNextSetAsync().Result } else { # Windows PowerShell $documentSet = $search.GetNextSet() } # Process the Document objects retrieves in this API call foreach ($document in $documentList) { # Do something with the document or print it for output stream ConvertFrom-Json -InputObject $document.ToJson() } } while ($search.IsDone -eq $false) } catch { # Take action on exception } finally { $ErrorActionPreference = $eap }
Code Sample: Delete an item from an Amazon DynamoDB Table# Uses the "dynamodb:DeleteItem" IAM Policy. # Create a Document object from a json string. $json = ConvertTo-Json -Compress -InputObject @{ id = 'MyHashKeyValue' } $document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json) # Perform the PutItem operation. Note the PowerShell Core request is asynchronous. if ($PSEdition -eq 'Core') { # PowerShell Core $table.DeleteItemAsync($document) } else { # Windows PowerShell $table.DeleteItem($document) }
Code Sample: Delete an Amazon DynamoDB Table# Uses the "dynamodb:DeleteTable" IAM Policy. Remove-DDBTable -TableName $tableName -Force
Code Sample: Expression StatementsWhen performing conditional actions, you need to specify an Expression Statement. Below are sample Expression Statements.$key = 'HashKey' $value = 'HashValue' $expression = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Expression # Key Begins With $expression.ExpressionStatement = "begins_with ($key, :evaluation)" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key Contains $expression.ExpressionStatement = "contains ($key, :evaluation)" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key Is Not Equal $expression.ExpressionStatement = "$key <> :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key Does Not Exist $expression.ExpressionStatement = "attribute_not_exists ($key)" # Key Exists $expression.ExpressionStatement = "attribute_exists ($key)" # Key Is Equal To $expression.ExpressionStatement = "$key = :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key Is Greater Than $expression.ExpressionStatement = "$key > :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key Is Greater Than or Equal To $expression.ExpressionStatement = "$key >= :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key Is Less Than $expression.ExpressionStatement = "$key < :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key Is Less Than or Equal To $expression.ExpressionStatement = "$key <= :evaluation" $expression.ExpressionAttributeValues[':evaluation'] = $value # Key is between two values $lowValue = 2 $highValue = 10 $expression.ExpressionStatement = "$key BETWEEN :lowvalue AND :highvalue" $expression.ExpressionAttributeValues[':lowvalue'] = $lowValue $expression.ExpressionAttributeValues[':highvalue'] = $highValue