To help you get started, here you will find our collection of the most popular .NET code samples and references to deeper dives on documentation with more detail. Check out samples below organized by category and then by service name. Get started with .NET or PowerShell.

Select
  • Select
  • .NET Code Samples
  • PowerShell Code Samples

.NET Code Samples

  • Authentication
  • Communications
  • Deployment
  • Storage
  • Authentication
  • Code Sample: Set up Amazon Cognito AWS Credentials
                CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                    accountId,        // Account number
                    identityPoolId,   // Identity pool ID
                    unAuthRoleArn,    // Role for unauthenticated users
                    null,             // Role for authenticated users, not set
                    region);
                using (var s3Client = new AmazonS3Client(credentials))
                {
                    //if using .NET Core, make sure to use await keyword and async method
                    s3Client.ListBuckets();
                }
    Code Sample: Use AWS as an Unauthenticated User
      CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                    accountId, identityPoolId,
                    unAuthRoleArn,    // Role for unauthenticated users
                    authRoleArn,      // Role for authenticated users
                    region);
                using (var s3Client = new AmazonS3Client(credentials))
                {
                     //if using .NET Core, make sure to use await keyword and async method
                    // Initial use will be unauthenticated
                    s3Client.ListBuckets();
    
                    // Authenticate user through Facebook
                    string facebookToken = GetFacebookAuthToken();
    
                    // Add Facebook login to credentials. This clears the current AWS credentials
                    // and retrieves new AWS credentials using the authenticated role.
                    credentials.AddLogin("graph.facebook.com", facebookAccessToken);
    
                    // This call is performed with the authenticated role and credentials
                    s3Client.ListBuckets();
                }
    Code Sample: Use Basic Authentication
            public static async void GetCredsAsync()
            {
                AmazonCognitoIdentityProviderClient provider =
                    new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
                CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
                CognitoUser user = new CognitoUser("username", "clientID", userPool, provider);
                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                {
                    Password = "userPassword"
                };
    
                AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
                accessToken = authResponse.AuthenticationResult.AccessToken;
    
            }
    Code Sample: Authenticate with Challenges
            public static async void GetCredsChallengesAsync()
            {
                AmazonCognitoIdentityProviderClient provider = 
                    new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
                CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
                CognitoUser user = new CognitoUser("username", "clientID", userPool, provider);
                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest(){
                    Password = "userPassword"
                };
    
                AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
    
                while (authResponse.AuthenticationResult == null)
                {
                    if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                    {
                        Console.WriteLine("Enter your desired new password:");
                        string newPassword = Console.ReadLine();
    
                        authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                        {
                            SessionID = authResponse.SessionID,
                            NewPassword = newPassword
                        });
                        accessToken = authResponse.AuthenticationResult.AccessToken;
                    }
                    else if (authResponse.ChallengeName == ChallengeNameType.SMS_MFA)
                    {
                        Console.WriteLine("Enter the MFA Code sent to your device:");
                        string mfaCode = Console.ReadLine();
    
                        AuthFlowResponse mfaResponse = await user.RespondToSmsMfaAuthAsync(new RespondToSmsMfaRequest()
                        {
                            SessionID = authResponse.SessionID,
                            MfaCode = mfaCode
    
                        }).ConfigureAwait(false);
                        accessToken = authResponse.AuthenticationResult.AccessToken;
                    }
                    else
                    {
                        Console.WriteLine("Unrecognized authentication challenge.");
                        accessToken = "";
                        break;
                    }
                }
    
                if (authResponse.AuthenticationResult != null)
                {
                    Console.WriteLine("User successfully authenticated.");
                }
                else
                {
                    Console.WriteLine("Error in authentication process.");
                }
             
            }
  • Communications
    • Amazon SQS
    • Amazon SNS
    • Amazon SES
    • Amazon SQS
    • Code Sample: Create an Amazon SQS Client
      //config
      AmazonSQSConfig sqsConfig = new AmazonSQSConfig();
      
      sqsConfig.ServiceURL = "http://sqs.us-west-2.amazonaws.com";
      
      //instantiate client
      AmazonSQSClient sqsClient = new AmazonSQSClient(sqsConfig);
      Code Sample: Create an Amazon SQS Queue and Construct an Amazon SQS Queue Url
      //initialize CreateQueueRequest instance
      
      CreateQueueRequest createQueueRequest = new CreateQueueRequest();
      
      createQueueRequest.QueueName = "MySQSQueue";
      Dictionary<string, string> attrs = new Dictionary<string, string>();
      attrs.Add(QueueAttributeName.VisibilityTimeout, "10");
      createQueueRequest.Attributes = attrs;
      
      //if using .NET Core, make sure to use await keyword and async method
      //pass request as a param to CreateQueue method
      CreateQueueResponse createQueueResponse = sqsClient.CreateQueue(createQueueRequest);
      
      //create the sqs queue url to use for sending, receiving, deleting sqs messages
      GetQueueUrlRequest request = new GetQueueUrlRequest
      {
        QueueName = "MyTestQueue",
        QueueOwnerAWSAccountId = "80398EXAMPLE"
      };
      var response = sqsClient.GetQueueUrl(request);
      Console.WriteLine("Queue URL: " + response.QueueUrl);
      Code Sample: Send an Amazon SQS Message or Message Batch
      //send one message
      //step 1 create and initialize a SendMessageRequest instance
      
      SendMessageRequest sendMessageRequest = new SendMessageRequest();
      sendMessageRequest.QueueUrl = myQueueURL; 
      sendMessageRequest.MessageBody = "{YOUR_QUEUE_MESSAGE}";
      
      //step 2 pass your request as a param to the SendMessage method
      
      SendMessageResponse sendMessageResponse = sqsClient.SendMessage(sendMessageRequest);
      
      //send batch of messsages
      //step 1 create and intialize a SendMessageRequestInstance with a list of messages
      
      var sendMessageBatchRequest = new SendMessageBatchRequest
      {
          Entries = new List<SendMessageBatchRequestEntry>
          {
              new SendMessageBatchRequestEntry("message1", "FirstMessageContent"),
              new SendMessageBatchRequestEntry("message2", "SecondMessageContent"),
              new SendMessageBatchRequestEntry("message3", "ThirdMessageContent")
          },
          QueueUrl = "SQS_QUEUE_URL"
      };
      
      //if using .NET Core, make sure to use await keyword and async method
      //step 2 pass the request as a param to the SendMessage method
      
      SendMessageBatchResponse response = client.SendMessageBatch(sendMessageBatchRequest);
      Console.WriteLine("Messages successfully sent:");
      foreach (var success in response.Successful)
      {
          Console.WriteLine("    Message id : {0}", success.MessageId);
          Console.WriteLine("    Message content MD5 : {0}", success.MD5OfMessageBody);
      }
      
      Console.WriteLine("Messages failed to send:");
      foreach (var failed in response.Failed)
      {
          Console.WriteLine("    Message id : {0}", failed.Id);
          Console.WriteLine("    Message content : {0}", failed.Message);
          Console.WriteLine("    Sender's fault? : {0}", failed.SenderFault);
      }
      Code Sample: Receive a message from an Amazon SQS Queue
      //create and initialize a ReceiveMessageRequest instance
      ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
      
      receiveMessageRequest.QueueUrl = myQueueURL;
      
      //if using .NET Core, make sure to use await keyword and async method
      //pass the request as a param to the ReceiveMessage method
      var receiveMessageResponse = sqsClient.ReceiveMessage(receiveMessageRequest);
      
      //
      foreach (var message in receiveMessageResponse.Messages)
      {
         // call a method to process messages and pass in message
      }
      Code Sample: Delete a Message from an Amazon SQS Queue
      //create and initialize a DeleteMessageRequest instance
      DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
      
      deleteMessageRequest.QueueUrl = queueUrl;
      deleteMessageRequest.ReceiptHandle = receiptHandle;
      
      //if using .NET Core, make sure to use await keyword and async method
      //pass the request as a param to the DeleteMessage method.
      var response = sqsClient.DeleteMessage(deleteMessageRequest);
    • Amazon SNS
    • Code Sample: List Amazon SNS Topics
      // using Amazon.SimpleNotificationService;
      // using Amazon.SimpleNotificationService.Model;
      
      var client = new AmazonSimpleNotificationServiceClient();
      var request = new ListTopicsRequest();
      var response = new ListTopicsResponse();
      
      do
      {
      //if using .NET Core, make sure to use await keyword and async method
        response = client.ListTopics(request);
      
        foreach (var topic in response.Topics)
        {
          Console.WriteLine("Topic: {0}", topic.TopicArn);
      
          var subs = client.ListSubscriptionsByTopic(
            new ListSubscriptionsByTopicRequest
            {
              TopicArn = topic.TopicArn
            });
      
          var ss = subs.Subscriptions;
      
          if (ss.Any())
          {
            Console.WriteLine("  Subscriptions:");
      
            foreach (var sub in ss)
            {
              Console.WriteLine("    {0}", sub.SubscriptionArn);
            }
          }
      
          var attrs = client.GetTopicAttributes(
            new GetTopicAttributesRequest
            {
              TopicArn = topic.TopicArn
            }).Attributes;
      
          if (attrs.Any())
          {
            Console.WriteLine("  Attributes:");
      
            foreach (var attr in attrs)
            {
              Console.WriteLine("    {0} = {1}", attr.Key, attr.Value);
            }
          }
      
          Console.WriteLine();
        }
      
        request.NextToken = response.NextToken;
      
      } while (!string.IsNullOrEmpty(response.NextToken));
      Code Sample: Create/Delete Topic
      //if using .NET Core, make sure to use await keyword and async method
      // Create topic
      string topicArn = client.CreateTopic(new CreateTopicRequest
      {
          Name = topicName
      }).CreateTopicResult.TopicArn;
      
      // Delete topic
      client.DeleteTopic(new DeleteTopicRequest
      {
          TopicArn = topicArn
      });
      Code Sample: Subscribe to an Endpoint
      //if using .NET Core, make sure to use await keyword and async method
      client.Subscribe(new SubscribeRequest
      {
          TopicArn = topicArn,
          Protocol = "email",
          Endpoint = "sample@example.com"
      });
      Code Sample: Publish a message
      //if using .NET Core, make sure to use await keyword and async method
      client.Publish(new PublishRequest
      {
          Subject = "Test",
          Message = "Testing testing 1 2 3",
          TopicArn = topicArn
      });
      
    • Amazon SES
    • Code Sample: Send an Email
                  // Replace sender@example.com with your "From" address. 
                  // This address must be verified with Amazon SES.
                  const String FROM = "sender@example.com";
                  const String FROMNAME = "Sender Name";
      
                  // Replace recipient@example.com with a "To" address. If your account 
                  // is still in the sandbox, this address must be verified.
                  const String TO = "recipient@example.com";
      
                  // Replace smtp_username with your Amazon SES SMTP user name.
                  const String SMTP_USERNAME = "smtp_username";
      
                  // Replace smtp_password with your Amazon SES SMTP user name.
                  const String SMTP_PASSWORD = "smtp_password";
      
                  // (Optional) the name of a configuration set to use for this message.
                  // If you comment out this line, you also need to remove or comment out
                  // the "X-SES-CONFIGURATION-SET" header below.
                  const String CONFIGSET = "ConfigSet";
      
                  // If you're using Amazon SES in a region other than US West (Oregon), 
                  // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP  
                  // endpoint in the appropriate Region.
                  const String HOST = "email-smtp.us-west-2.amazonaws.com";
                  
                  // The port you will connect to on the Amazon SES SMTP endpoint. We
                  // are choosing port 587 because we will use STARTTLS to encrypt
                  // the connection.
                  const int PORT = 587;
      
                  // The subject line of the email
                  const String SUBJECT =
                      "Amazon SES test (SMTP interface accessed using C#)";
                  
                  // The body of the email
                  const String BODY =
                      "<h1>Amazon SES Test</h1>" +
                      "<p>This email was sent through the "+
                      "<a href='https://aws.amazon.com/ses'>Amazon SES</a> SMTP interface " +
                      "using the .NET System.Net.Mail library.</p>";
      
                  // Create and build a new MailMessage object
                  MailMessage message = new MailMessage();
                  message.IsBodyHtml = true;
                  message.From = new MailAddress(FROM,FROMNAME);
                  message.To.Add(new MailAddress(TO));
                  message.Subject = SUBJECT;
                  message.Body = BODY;
                  // Comment or delete the next line if you are not using a configuration set
                  message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);
      
                  // Create and configure a new SmtpClient
                  SmtpClient client =
                      new SmtpClient(HOST, PORT);
                  // Pass SMTP credentials
                  client.Credentials =
                      new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
                  // Enable SSL encryption
                  client.EnableSsl = true;
                   
                   //if using .NET Core, make sure to use await keyword and async method
                  // Send the email. 
                  try
                  {
                      Console.WriteLine("Attempting to send email...");
                      client.Send(message);
                      Console.WriteLine("Email sent!");
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine("The email was not sent.");
                      Console.WriteLine("Error message: " + ex.Message);
                  }
  • Deployment
  • Code Sample: Launch an Amazon EC2 Instance in EC2-Classic
    ///create an ec2 client
    var ec2Client = new AmazonEC2Client();
    
    //step 1- initialize a RunInstancesRequest
    string amiID = "ami-e189c8d1";
    string keyPairName = "my-sample-key";
    
    //optional to launch instance with IAM role
    var instanceProfile = new IamInstanceProfile();
    instanceProfile.Id  = "winapp-instance-role-1";
    
    List<string> groups = new List<string>() { mySG.GroupId };
    var launchRequest = new RunInstancesRequest()
    {
      ImageId = amiID,
      InstanceType = InstanceType.T1Micro,
      MinCount = 1,
      MaxCount = 1,
      KeyName = keyPairName,
      SecurityGroupIds = groups,
      IamInstanceProfile = instanceProfile //optional property
    };
    
    //if using .NET Core, make sure to use await keyword and async method
    //step 2 launch the instance by passing the request object to the RunInstances Method
    
    var launchResponse = ec2Client.RunInstances(launchRequest);
    var instances = launchResponse.Reservation.Instances;
    var instanceIds = new List<string>();
    foreach (Instance item in instances)
    {
      instanceIds.Add(item.InstanceId);
      Console.WriteLine();
      Console.WriteLine("New instance: " + item.InstanceId);
      Console.WriteLine("Instance state: " + item.State.Name);
    }
    
    
    
    
    Code Sample: Launch an Amazon EC2 Instance in a VPC
    ///create an ec2 client
    var ec2Client = new AmazonEC2Client();
    
    //step 1- create and initialize an elastic network interface in a subnet of the VPC
    
    string subnetID = "subnet-cb663da2";
    
    List<string> groups = new List<string>() { mySG.GroupId };
    var eni = new InstanceNetworkInterfaceSpecification()
    {
      DeviceIndex = 0,
      SubnetId = subnetID,
      Groups = groups,
      AssociatePublicIpAddress = true
    };
    List<InstanceNetworkInterfaceSpecification> enis = new List<InstanceNetworkInterfaceSpecification>() {eni};
    
    //step 2 create and initialize a RunInstancesRequest object
    
    string amiID = "ami-e189c8d1";
    string keyPairName = "my-sample-key";
    
    //optional lines to launch with an IAM role
    
    var instanceProfile = new IamInstanceProfileSpecification();
    instanceProfile.Name  = "winapp-instance-role-1";
    
    var launchRequest = new RunInstancesRequest()
    {
      ImageId = amiID,
      InstanceType = InstanceType.T1Micro,
      MinCount = 1,
      MaxCount = 1,
      KeyName = keyPairName,
      NetworkInterfaces = enis,
      IamInstanceProfile = instanceProfile //optional property to launch with iam role
    };
    
    //if using .NET Core, make sure to use await keyword and async method
    //step 3 launch the instance by passing the request object to the RunInstances Method
    
    RunInstancesResponse launchResponse = ec2Client.RunInstances(launchRequest);
    
    List<String> instanceIds = new List<string>();
    foreach (Instance instance in launchResponse.Reservation.Instances)
    {
      Console.WriteLine(instance.InstanceId);
      instanceIds.Add(instance.InstanceId);
    }
    Code Sample: Terminate an Amazon EC2 Instance
    public static void TerminateInstance(
      AmazonEC2Client ec2Client,
      string instanceId)
    {
      //if using .NET Core, make sure to use await keyword and async method
      var request = new TerminateInstancesRequest();
      request.InstanceIds = new List<string>() { instanceId };
    
      try
      {
        var response = ec2Client.TerminateInstances(request);
        foreach (InstanceStateChange item in response.TerminatingInstances)
        {
          Console.WriteLine("Terminated instance: " + item.InstanceId);
          Console.WriteLine("Instance state: " + item.CurrentState.Name);
        }
      }
      catch(AmazonEC2Exception ex)
      {
        // Check the ErrorCode to see if the instance does not exist.
        if ("InvalidInstanceID.NotFound" == ex.ErrorCode)
        {
          Console.WriteLine("Instance {0} does not exist.", instanceId);
        }
        else
        {
          // The exception was thrown for another reason, so re-throw the exception.
          throw;
        }
      }
    }
  • Storage
    • Amazon DynamoDb
    • Amazon S3
    • Amazon Glacier
    • Amazon DynamoDb
    • Code Samples for Object Persistence Model

      Code Sample: Defining a .NET Class that Represents an Item in a Table
      // using Amazon.DynamoDBv2.DataModel;
      
      [DynamoDBTable("AnimalsInventory")]
      class Item
      {
        [DynamoDBHashKey]
        public int Id { get; set; }
        [DynamoDBRangeKey]
        public string Type { get; set; }
        public string Name { get; set; }
      }
      Using an Instance of the .NET Class to Insert an Item into a Table
      //Insert into DynamoTable using Object Persistence Model
      
      // using Amazon.DynamoDBv2;
      // using Amazon.DynamoDBv2.DataModel;
          
      var client = new AmazonDynamoDBClient();
      var context = new DynamoDBContext(client);
      var item = new Item
      {
        Id = 4,
        Type = "Fish",
        Name = "Goldie"
      };
      
      //if using .NET Core, make sure to use await keyword and async method
      context.Save(item);
      Using an Instance of a .NET Object to Get an Item from a Table
      // using Amazon.DynamoDBv2;
      // using Amazon.DynamoDBv2.DataModel;
      
      var client = new AmazonDynamoDBClient();
      var context = new DynamoDBContext(client);
      //if using .NET Core, make sure to use await keyword and async method of Load
      var item = context.Load<Item>(4, "Fish");
      
      Console.WriteLine("Id = {0}", item.Id);
      Console.WriteLine("Type = {0}", item.Type);
      Console.WriteLine("Name = {0}", item.Name);
    • Amazon S3
    • Code Sample: Create a Bucket
      using Amazon.S3;
      using Amazon.S3.Model;
      using Amazon.S3.Util;
      using System;
      using System.Threading.Tasks;
      
      namespace Amazon.DocSamples.S3
      {
          class CreateBucketTest
          {
              private const string bucketName = "*** bucket name ***";
              // Specify your bucket region (an example region is shown).
              private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
              private static IAmazonS3 s3Client;
              public static void Main()
              {
                  s3Client = new AmazonS3Client(bucketRegion);
                  CreateBucketAsync().Wait();
              }
      
              static async Task CreateBucketAsync()
              {
                  try
                  {
                      if (!(await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName)))
                      {
                          var putBucketRequest = new PutBucketRequest
                          {
                              BucketName = bucketName,
                              UseClientRegion = true
                          };
      
                          PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest);
                      }
                      // Retrieve the bucket location.
                      string bucketLocation = await FindBucketLocationAsync(s3Client);
                  }
                  catch (AmazonS3Exception e)
                  {
                      Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
                  }
                  catch (Exception e)
                  {
                      Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                  }
              }
              static async Task<string> FindBucketLocationAsync(IAmazonS3 client)
              {
                  string bucketLocation;
                  var request = new GetBucketLocationRequest()
                  {
                      BucketName = bucketName
                  };
                  GetBucketLocationResponse response = await client.GetBucketLocationAsync(request);
                  bucketLocation = response.Location.ToString();
                  return bucketLocation;
              }
          }
      }
      Code Sample: Upload Object in a Single Operation
      using Amazon.S3;
      using Amazon.S3.Model;
      using System;
      using System.Threading.Tasks;
      
      namespace Amazon.DocSamples.S3
      {
          class UploadObjectTest
          {
              private const string bucketName = "*** bucket name ***";
              // Example creates two objects (for simplicity, we upload same file twice).
              // You specify key names for these objects.
              private const string keyName1 = "*** key name for first object created ***";
              private const string keyName2 = "*** key name for second object created ***";
              private const string filePath = @"*** file path ***";
              private static readonly RegionEndpoint bucketRegion = RegionEndpoint.EUWest1; 
      
              private static IAmazonS3 client;
      
              public static void Main()
              {
                  client = new AmazonS3Client(bucketRegion);
                  WritingAnObjectAsync().Wait();
              }
      
              static async Task WritingAnObjectAsync()
              {
                  try
                  {
                      // 1. Put object-specify only key name for the new object.
                      var putRequest1 = new PutObjectRequest
                      {
                          BucketName = bucketName,
                          Key = keyName1,
                          ContentBody = "sample text"
                      };
      
                      PutObjectResponse response1 = await client.PutObjectAsync(putRequest1);
      
                      // 2. Put the object-set ContentType and add metadata.
                      var putRequest2 = new PutObjectRequest
                      {
                          BucketName = bucketName,
                          Key = keyName2,
                          FilePath = filePath,
                          ContentType = "text/plain"
                      };
                      putRequest2.Metadata.Add("x-amz-meta-title", "someTitle");
                  }
                  catch (AmazonS3Exception e)
                  {
                      Console.WriteLine(
                              "Error encountered ***. Message:'{0}' when writing an object"
                              , e.Message);
                  }
                  catch (Exception e)
                  {
                      Console.WriteLine(
                          "Unknown encountered on server. Message:'{0}' when writing an object"
                          , e.Message);
                  }
              }
          }
      }
      Code Sample: Upload Object using Multipart Upload - High Level API
      using Amazon.Runtime;
      using Amazon.S3;
      using Amazon.S3.Model;
      using System;
      using System.Collections.Generic;
      using System.IO;
      using System.Threading.Tasks;
      
      namespace Amazon.DocSamples.S3
      {
          class UploadFileMPULowLevelAPITest
          {
              private const string bucketName = "*** provide bucket name ***";
              private const string keyName = "*** provide a name for the uploaded object ***";
              private const string filePath = "*** provide the full path name of the file to upload ***";
              // Specify your bucket region (an example region is shown).
              private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
              private static IAmazonS3 s3Client;
      
              public static void Main()
              {
                  s3Client = new AmazonS3Client(bucketRegion);
                  Console.WriteLine("Uploading an object");
                  UploadObjectAsync().Wait(); 
              }
      
              private static async Task UploadObjectAsync()
              {
                  // Create list to store upload part responses.
                  List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
      
                  // Setup information required to initiate the multipart upload.
                  InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
                  {
                      BucketName = bucketName,
                      Key = keyName
                  };
      
                  // Initiate the upload.
                  InitiateMultipartUploadResponse initResponse =
                      await s3Client.InitiateMultipartUploadAsync(initiateRequest);
      
                  // Upload parts.
                  long contentLength = new FileInfo(filePath).Length;
                  long partSize = 5 * (long)Math.Pow(2, 20); // 5 MB
      
                  try
                  {
                      Console.WriteLine("Uploading parts");
              
                      long filePosition = 0;
                      for (int i = 1; filePosition < contentLength; i++)
                      {
                          UploadPartRequest uploadRequest = new UploadPartRequest
                              {
                                  BucketName = bucketName,
                                  Key = keyName,
                                  UploadId = initResponse.UploadId,
                                  PartNumber = i,
                                  PartSize = partSize,
                                  FilePosition = filePosition,
                                  FilePath = filePath
                              };
      
                          // Track upload progress.
                          uploadRequest.StreamTransferProgress +=
                              new EventHandler<StreamTransferProgressArgs>(UploadPartProgressEventCallback);
      
                          // Upload a part and add the response to our list.
                          uploadResponses.Add(await s3Client.UploadPartAsync(uploadRequest));
      
                          filePosition += partSize;
                      }
      
                      // Setup to complete the upload.
                      CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
                          {
                              BucketName = bucketName,
                              Key = keyName,
                              UploadId = initResponse.UploadId
                           };
                      completeRequest.AddPartETags(uploadResponses);
      
                      // Complete the upload.
                      CompleteMultipartUploadResponse completeUploadResponse =
                          await s3Client.CompleteMultipartUploadAsync(completeRequest);
                  }
                  catch (Exception exception)
                  {
                      Console.WriteLine("An AmazonS3Exception was thrown: { 0}", exception.Message);
      
                      // Abort the upload.
                      AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
                      {
                          BucketName = bucketName,
                          Key = keyName,
                          UploadId = initResponse.UploadId
                      };
                     await s3Client.AbortMultipartUploadAsync(abortMPURequest);
                  }
              }
              public static void UploadPartProgressEventCallback(object sender, StreamTransferProgressArgs e)
              {
                  // Process event. 
                  Console.WriteLine("{0}/{1}", e.TransferredBytes, e.TotalBytes);
              }
          }
      }
      
      Code Sample: Get Object
      //if using .NET Core, make sure to use await keyword and async method
      GetObjectRequest request = new GetObjectRequest 
      {
          BucketName = bucketName,
          Key = keyName
      };
      
      ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
      responseHeaders.CacheControl = "No-cache";
      responseHeaders.ContentDisposition = "attachment; filename=testing.txt";
      
      request.ResponseHeaderOverrides = responseHeaders;
      Code Sample: Delete Object from a NonVersioned Bucket
      using Amazon.S3;
      using Amazon.S3.Model;
      using System;
      using System.Threading.Tasks;
      
      namespace Amazon.DocSamples.S3
      {
          class DeleteObjectNonVersionedBucketTest
          {
              private const string bucketName = "*** bucket name ***"; 
              private const string keyName = "*** object key ***";
              // Specify your bucket region (an example region is shown).
              private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
              private static IAmazonS3 client;
      
              public static void Main()
              {
                  client = new AmazonS3Client(bucketRegion);
                  DeleteObjectNonVersionedBucketAsync().Wait();
              }
      
              private static async Task DeleteObjectNonVersionedBucketAsync()
              {
                  try
                  {
                      var deleteObjectRequest = new DeleteObjectRequest
                      {
                          BucketName = bucketName,
                          Key = keyName
                      };
      
                      Console.WriteLine("Deleting an object");
                      await client.DeleteObjectAsync(deleteObjectRequest);
                  }
                  catch (AmazonS3Exception e)
                  {
                      Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
                  }
                  catch (Exception e)
                  {
                      Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                  }
              }
          }
      }
    • Amazon Glacier
    • Code Sample: Create/Delete a Vault using High Level API
      using System;
      using Amazon.Glacier;
      using Amazon.Glacier.Transfer;
      using Amazon.Runtime;
      
      namespace glacier.amazon.com.docsamples
      {
        class VaultCreateDescribeListVaultsDeleteHighLevel
        {
          static string vaultName = "*** Provide vault name ***";
      
          public static void Main(string[] args)
          {
            try
            {
                var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2);
               //if using .NET Core, make sure to use await keyword and async methods
                manager.CreateVault(vaultName);
                Console.WriteLine("Vault created. To delete the vault, press Enter");
                Console.ReadKey();
                manager.DeleteVault(vaultName);
                Console.WriteLine("\nVault deleted. To continue, press Enter");
                Console.ReadKey();
            }
            catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }
            Console.WriteLine("To continue, press Enter");
            Console.ReadKey();
          }
        }
      }
      Code Sample: Retrieve Metadata for a Vault
      AmazonGlacierClient client;
      client = new AmazonGlacierClient(Amazon.RegionEndpoint.USWest2);
      
      DescribeVaultRequest describeVaultRequest = new DescribeVaultRequest()
      {
        VaultName = "*** Provide vault name ***"
      };  
      //if using .NET Core, make sure to use await keyword and async method
      DescribeVaultResponse describeVaultResponse = client.DescribeVault(describeVaultRequest);
      Console.WriteLine("\nVault description...");
      Console.WriteLine(
         "\nVaultName: " + describeVaultResponse.VaultName +
         "\nVaultARN: " + describeVaultResponse.VaultARN +
         "\nVaultCreationDate: " + describeVaultResponse.CreationDate +
         "\nNumberOfArchives: " + describeVaultResponse.NumberOfArchives +
         "\nSizeInBytes: " + describeVaultResponse.SizeInBytes +
         "\nLastInventoryDate: " + describeVaultResponse.LastInventoryDate 
         );
      Code Sample: Upload an Archive
      using System;
      using Amazon.Glacier;
      using Amazon.Glacier.Transfer;
      using Amazon.Runtime;
      
      namespace glacier.amazon.com.docsamples
      {
        class ArchiveUploadHighLevel
        {
          static string vaultName = "examplevault"; 
          static string archiveToUpload = "*** Provide file name (with full path) to upload ***";
      
          public static void Main(string[] args)
          {
             try
            {
               var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2);
               // Upload an archive.
               //if using .NET Core, make sure to use await keyword and async method
               string archiveId = manager.Upload(vaultName, "upload archive test", archiveToUpload).ArchiveId;
               Console.WriteLine("Archive ID: (Copy and save this ID for use in other examples.) : {0}", archiveId);
               Console.WriteLine("To continue, press Enter"); 
               Console.ReadKey();
            }
            catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }
            Console.WriteLine("To continue, press Enter");
            Console.ReadKey();
          }
        }
      }
      Code Sample: Delete an Archive using High Level API
      using System;
      using Amazon.Glacier;
      using Amazon.Glacier.Transfer;
      using Amazon.Runtime; 
      
      namespace glacier.amazon.com.docsamples
      {
        class ArchiveDeleteHighLevel
        {
          static string vaultName = "examplevault";
          static string archiveId = "*** Provide archive ID ***";
      
          public static void Main(string[] args)
          {
            try
            {
              var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2);
              //if using .NET Core, make sure to use await keyword and async method
              manager.DeleteArchive(vaultName, archiveId);
              Console.ReadKey();
            }
            catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }
            Console.WriteLine("To continue, press Enter");
            Console.ReadKey();
          }
        }
      }

PowerShell Code Samples

  • Monitoring
  • Communications
  • Serverless
  • Storage
  • 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:

    Get-CWLLogEvent

    New-CWLLogGroup

    New-CWLLogStream

    Remove-CWLLogGroup

    Remove-CWLLogStream

    Write-CWLLogEvent

    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.

    Code Sample: Create an Amazon CloudWatch Log Group
    # Uses the "logs:CreateLogGroup" IAM Policy.
    New-CWLLogGroup -LogGroupName 'MyLogGroup'
    Code Sample: Create an Amazon CloudWatch Log Stream
    # Uses the "logs:CreateLogStream" IAM Policy.
    $splat = @{
        LogGroupName = 'MyLogGroup'
        LogStreamName = 'MyLogStream'
    }
    New-CWLLogStream @splat
    Code Sample: Write a Log Entry to the Log Stream
    When writing a CloudWatch Log Event, the first log written to a Log Stream does not require a SequenceToken value, however this is a required property for all follow up writes. The next SequenceToken is returned from the Write-CWLLogEvent cmdlet.
    # 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
    Code Sample: Write a batch of Log Entries to a Log Stream

    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
    Code Sample: Exception Handling when writing a Log Entry to the a Log Stream

    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
            }
        }
    }
    Code Sample: Retrieve Amazon CloudWatch Logs starting at a specified time
    # 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
    Code Sample: Retrieve Amazon CloudWatch Logs within a time range
    $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
    }
    Code Sample: Remove an Amazon CloudWatch Log Stream
    # Uses the "logs:DeleteLogStream" IAM Policy.
    Remove-CWLLogStream -LogGroupName 'MyLogGroup' -LogStreamName 'MyLogStream' -Force
    Code Sample: Remove an Amazon CloudWatch Log Group
    # 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:

      Add-SQSPermission

      Get-SQSQueueUrl

      Get-SQSQueueAttribute

      New-SQSQueue

      Receive-SQSMessage

      Remove-SQSPermission

      Remove-SQSQueue

      Send-SQSMessage

      Send-SQSMessageBatch

      Set-SQSQueueAttribute

      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 Attributes

      More 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:

      Connect-SNSNotification

      Get-SNSSubscriptionByTopic

      Get-SNSTopic

      Get-SNSTopicAttribute

      Get-SQSQueueAttribute

      New-SNSTopic

      New-SQSQueue

      Publish-SNSMessage

      Remove-SNSTopic

      Set-SQSQueueAttribute

      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 Topic

      More 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:

      Invoke-LMFunction

      New-IAMPolicy

      New-IAMRole

      Publish-LMFunction

      Register-IAMRolePolicy

      Update-LMFunctionCode

      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 Variables
      This 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:

      Get-DefaultAWSRegion

      Get-SFNActivityTask

      Get-SFNExecution

      Get-SFNExecutionHistory

      Get-SFNExecutionList

      New-IAMPolicy

      New-IAMRole

      New-SFNActivity

      New-SFNStateMachine

      Register-IAMRolePolicy

      Remove-IAMPolicy

      Remove-IAMRole

      Remove-SFNActivity

      Remove-SFNStateMachine

      Send-SFNTaskFailure

      Send-SFNTaskHeartbeat

      Send-SFNTaskSuccess

      Start-SFNExecution

      Unregister-IAMRolePolicy

      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 Machine
      This 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:

      Add-DDBKeySchema

      New-DDBTableSchema

      New-DDBTable

      Remove-DDBTable

      The examples here use the following AWS SDK for .NET Namespaces:

      Amazon.RegionEndpoint

      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 Table
      Use 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 Table

      To 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 Table
      This 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 Table
      This 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 Table
      This 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 Table
      This 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 Statements
      When 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

Join a Virtual .NET Community