

There are more AWS SDK examples available in the [AWS Doc SDK Examples](https://github.com/awsdocs/aws-doc-sdk-examples) GitHub repo.

# Code examples for WorkSpaces using AWS SDKs
<a name="workspaces_code_examples"></a>

The following code examples show you how to use Amazon WorkSpaces with an AWS software development kit (SDK).

*Actions* are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios.

*Scenarios* are code examples that show you how to accomplish specific tasks by calling multiple functions within a service or combined with other AWS services.

**More resources**
+  **[ WorkSpaces Developer Guide](https://docs.aws.amazon.com/workspaces/latest/userguide/workspaces-user-getting-started.html)** – More information about WorkSpaces.
+ **[WorkSpaces API Reference](https://docs.aws.amazon.com/workspaces/latest/api/welcome.html)** – Details about all available WorkSpaces actions.
+ **[AWS Developer Center](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23)** – Code examples that you can filter by category or full-text search.
+ **[AWS SDK Examples](https://github.com/awsdocs/aws-doc-sdk-examples)** – GitHub repo with complete code in preferred languages. Includes instructions for setting up and running the code.

**Contents**
+ [Basics](workspaces_code_examples_basics.md)
  + [Actions](workspaces_code_examples_actions.md)
    + [`CreateTags`](workspaces_example_workspaces_CreateTags_section.md)
    + [`CreateWorkspaces`](workspaces_example_workspaces_CreateWorkspaces_section.md)
    + [`DeleteTags`](workspaces_example_workspaces_DeleteTags_section.md)
    + [`DescribeTags`](workspaces_example_workspaces_DescribeTags_section.md)
    + [`DescribeWorkspaceBundles`](workspaces_example_workspaces_DescribeWorkspaceBundles_section.md)
    + [`DescribeWorkspaceDirectories`](workspaces_example_workspaces_DescribeWorkspaceDirectories_section.md)
    + [`DescribeWorkspaces`](workspaces_example_workspaces_DescribeWorkspaces_section.md)
    + [`DescribeWorkspacesConnectionStatus`](workspaces_example_workspaces_DescribeWorkspacesConnectionStatus_section.md)
    + [`ModifyWorkspaceCreationProperties`](workspaces_example_workspaces_ModifyWorkspaceCreationProperties_section.md)
    + [`ModifyWorkspaceProperties`](workspaces_example_workspaces_ModifyWorkspaceProperties_section.md)
    + [`ModifyWorkspaceState`](workspaces_example_workspaces_ModifyWorkspaceState_section.md)
    + [`RebootWorkspaces`](workspaces_example_workspaces_RebootWorkspaces_section.md)
    + [`RebuildWorkspaces`](workspaces_example_workspaces_RebuildWorkspaces_section.md)
    + [`RegisterWorkspaceDirectory`](workspaces_example_workspaces_RegisterWorkspaceDirectory_section.md)
    + [`StopWorkspaces`](workspaces_example_workspaces_StopWorkspaces_section.md)
    + [`TerminateWorkspaces`](workspaces_example_workspaces_TerminateWorkspaces_section.md)
+ [Scenarios](workspaces_code_examples_scenarios.md)
  + [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md)

# Basic examples for WorkSpaces using AWS SDKs
<a name="workspaces_code_examples_basics"></a>

The following code examples show how to use the basics of Amazon WorkSpaces with AWS SDKs. 

**Contents**
+ [Actions](workspaces_code_examples_actions.md)
  + [`CreateTags`](workspaces_example_workspaces_CreateTags_section.md)
  + [`CreateWorkspaces`](workspaces_example_workspaces_CreateWorkspaces_section.md)
  + [`DeleteTags`](workspaces_example_workspaces_DeleteTags_section.md)
  + [`DescribeTags`](workspaces_example_workspaces_DescribeTags_section.md)
  + [`DescribeWorkspaceBundles`](workspaces_example_workspaces_DescribeWorkspaceBundles_section.md)
  + [`DescribeWorkspaceDirectories`](workspaces_example_workspaces_DescribeWorkspaceDirectories_section.md)
  + [`DescribeWorkspaces`](workspaces_example_workspaces_DescribeWorkspaces_section.md)
  + [`DescribeWorkspacesConnectionStatus`](workspaces_example_workspaces_DescribeWorkspacesConnectionStatus_section.md)
  + [`ModifyWorkspaceCreationProperties`](workspaces_example_workspaces_ModifyWorkspaceCreationProperties_section.md)
  + [`ModifyWorkspaceProperties`](workspaces_example_workspaces_ModifyWorkspaceProperties_section.md)
  + [`ModifyWorkspaceState`](workspaces_example_workspaces_ModifyWorkspaceState_section.md)
  + [`RebootWorkspaces`](workspaces_example_workspaces_RebootWorkspaces_section.md)
  + [`RebuildWorkspaces`](workspaces_example_workspaces_RebuildWorkspaces_section.md)
  + [`RegisterWorkspaceDirectory`](workspaces_example_workspaces_RegisterWorkspaceDirectory_section.md)
  + [`StopWorkspaces`](workspaces_example_workspaces_StopWorkspaces_section.md)
  + [`TerminateWorkspaces`](workspaces_example_workspaces_TerminateWorkspaces_section.md)

# Actions for WorkSpaces using AWS SDKs
<a name="workspaces_code_examples_actions"></a>

The following code examples demonstrate how to perform individual WorkSpaces actions with AWS SDKs. Each example includes a link to GitHub, where you can find instructions for setting up and running the code. 

These excerpts call the WorkSpaces API and are code excerpts from larger programs that must be run in context. You can see actions in context in [Scenarios for WorkSpaces using AWS SDKs](workspaces_code_examples_scenarios.md). 

 The following examples include only the most commonly used actions. For a complete list, see the [Amazon WorkSpaces API Reference](https://docs.aws.amazon.com/workspaces/latest/api/welcome.html). 

**Topics**
+ [`CreateTags`](workspaces_example_workspaces_CreateTags_section.md)
+ [`CreateWorkspaces`](workspaces_example_workspaces_CreateWorkspaces_section.md)
+ [`DeleteTags`](workspaces_example_workspaces_DeleteTags_section.md)
+ [`DescribeTags`](workspaces_example_workspaces_DescribeTags_section.md)
+ [`DescribeWorkspaceBundles`](workspaces_example_workspaces_DescribeWorkspaceBundles_section.md)
+ [`DescribeWorkspaceDirectories`](workspaces_example_workspaces_DescribeWorkspaceDirectories_section.md)
+ [`DescribeWorkspaces`](workspaces_example_workspaces_DescribeWorkspaces_section.md)
+ [`DescribeWorkspacesConnectionStatus`](workspaces_example_workspaces_DescribeWorkspacesConnectionStatus_section.md)
+ [`ModifyWorkspaceCreationProperties`](workspaces_example_workspaces_ModifyWorkspaceCreationProperties_section.md)
+ [`ModifyWorkspaceProperties`](workspaces_example_workspaces_ModifyWorkspaceProperties_section.md)
+ [`ModifyWorkspaceState`](workspaces_example_workspaces_ModifyWorkspaceState_section.md)
+ [`RebootWorkspaces`](workspaces_example_workspaces_RebootWorkspaces_section.md)
+ [`RebuildWorkspaces`](workspaces_example_workspaces_RebuildWorkspaces_section.md)
+ [`RegisterWorkspaceDirectory`](workspaces_example_workspaces_RegisterWorkspaceDirectory_section.md)
+ [`StopWorkspaces`](workspaces_example_workspaces_StopWorkspaces_section.md)
+ [`TerminateWorkspaces`](workspaces_example_workspaces_TerminateWorkspaces_section.md)

# Use `CreateTags` with a CLI
<a name="workspaces_example_workspaces_CreateTags_section"></a>

The following code examples show how to use `CreateTags`.

------
#### [ CLI ]

**AWS CLI**  
**To add tags to a WorkSpace**  
The following `create-tags` example adds the specified tags to the specified WorkSpace.  

```
aws workspaces create-tags \
    --resource-id ws-dk1xzr417 \
    --tags Key=Department,Value=Finance
```
This command produces no output.  
For more information, see [Tag WorkSpaces resources](https://docs.aws.amazon.com/workspaces/latest/adminguide/tag-workspaces-resources.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [CreateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/create-tags.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This example adds a new tag to a workspace named `ws-wsname`. The tag has a key of "Name", and a key value of `AWS_Workspace`.**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag
```
**Example 2: This example adds multiple tags to a workspace named `ws-wsname`. One tag has a key of "Name" and a key value of `AWS_Workspace`; the other tag has a tag key of "Stage" and a key value of "Test".**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"

$tag2 = New-Object Amazon.WorkSpaces.Model.Tag
$tag2.Key = "Stage"
$tag2.Value = "Test"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag,$tag2
```
+  For API details, see [CreateTags](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This example adds a new tag to a workspace named `ws-wsname`. The tag has a key of "Name", and a key value of `AWS_Workspace`.**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag
```
**Example 2: This example adds multiple tags to a workspace named `ws-wsname`. One tag has a key of "Name" and a key value of `AWS_Workspace`; the other tag has a tag key of "Stage" and a key value of "Test".**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"

$tag2 = New-Object Amazon.WorkSpaces.Model.Tag
$tag2.Key = "Stage"
$tag2.Value = "Test"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag,$tag2
```
+  For API details, see [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `CreateWorkspaces` with a CLI
<a name="workspaces_example_workspaces_CreateWorkspaces_section"></a>

The following code examples show how to use `CreateWorkspaces`.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: 
+  [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**Example 1: To create an AlwaysOn WorkSpace**  
The following `create-workspaces` example creates an AlwaysOn WorkSpace for the specified user, using the specified directory and bundle.  

```
aws workspaces create-workspaces \
    --workspaces DirectoryId=d-926722edaf,UserName=Mateo,BundleId=wsb-0zsvgp8fc
```
Output:  

```
{
    "FailedRequests": [],
    "PendingRequests": [
        {
            "WorkspaceId": "ws-kcqms853t",
            "DirectoryId": "d-926722edaf",
            "UserName": "Mateo",
            "State": "PENDING",
            "BundleId": "wsb-0zsvgp8fc"
        }
    ]
}
```
**Example 2: To create an AutoStop WorkSpace**  
The following `create-workspaces` example creates an AutoStop WorkSpace for the specified user, using the specified directory and bundle.  

```
aws workspaces create-workspaces \
    --workspaces DirectoryId=d-926722edaf,UserName=Mary,BundleId=wsb-0zsvgp8fc,WorkspaceProperties={RunningMode=AUTO_STOP}
```
Output:  

```
{
    "FailedRequests": [],
    "PendingRequests": [
        {
            "WorkspaceId": "ws-dk1xzr417",
            "DirectoryId": "d-926722edaf",
            "UserName": "Mary",
            "State": "PENDING",
            "BundleId": "wsb-0zsvgp8fc"
        }
    ]
}
```
**Example 3: To create a user-decoupled WorkSpace**  
The following `create-workspaces` example creates a user-decoupled WorkSpace by setting the username to `[UNDEFINED]`, and specifying a WorkSpace name, directory ID, and bundle ID.  

```
aws workspaces create-workspaces \
    --workspaces DirectoryId=d-926722edaf,UserName='"[UNDEFINED]"',WorkspaceName=MaryWorkspace1,BundleId=wsb-0zsvgp8fc,WorkspaceProperties={RunningMode=ALWAYS_ON}
```
Output:  

```
{
    "FailedRequests": [],
    "PendingRequests": [
        {
            "WorkspaceId": "ws-abcd1234",
            "DirectoryId": "d-926722edaf",
            "UserName": "[UNDEFINED]",
            "State": "PENDING",
            "BundleId": "wsb-0zsvgp8fc",
            "WorkspaceName": "MaryWorkspace1"
        }
    ]
}
```
For more information, see [Launch a virtual desktop](https://docs.aws.amazon.com/workspaces/latest/adminguide/launch-workspaces-tutorials.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [CreateWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/create-workspaces.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Create a WorkSpace for the supplied bundle, directory, and user.**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME"}
```
**Example 2: This example creates multiple WorkSpaces**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_1"},@{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_2"}
```
+  For API details, see [CreateWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Create a WorkSpace for the supplied bundle, directory, and user.**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME"}
```
**Example 2: This example creates multiple WorkSpaces**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_1"},@{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_2"}
```
+  For API details, see [CreateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `DeleteTags` with a CLI
<a name="workspaces_example_workspaces_DeleteTags_section"></a>

The following code examples show how to use `DeleteTags`.

------
#### [ CLI ]

**AWS CLI**  
**To delete a tag from a WorkSpace**  
The following `delete-tags` example deletes the specified tag from the specified WorkSpace.  

```
aws workspaces delete-tags \
    --resource-id ws-dk1xzr417 \
    --tag-keys Department
```
This command produces no output.  
For more information, see [Tag WorkSpaces resources](https://docs.aws.amazon.com/workspaces/latest/adminguide/tag-workspaces-resources.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [DeleteTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/delete-tags.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This sample removes the tag associated with the Workspace**  

```
Remove-WKSTag -ResourceId ws-w10b3abcd -TagKey "Type"
```
**Output:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSTag (DeleteTags)" on target "ws-w10b3abcd".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  For API details, see [DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This sample removes the tag associated with the Workspace**  

```
Remove-WKSTag -ResourceId ws-w10b3abcd -TagKey "Type"
```
**Output:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSTag (DeleteTags)" on target "ws-w10b3abcd".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  For API details, see [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `DescribeTags` with a CLI
<a name="workspaces_example_workspaces_DescribeTags_section"></a>

The following code examples show how to use `DescribeTags`.

------
#### [ CLI ]

**AWS CLI**  
**To describe the tags for a WorkSpace**  
The following `describe-tags` example describes the tags for the specified WorkSpace.  

```
aws workspaces describe-tags \
    --resource-id ws-dk1xzr417
```
Output:  

```
{
    "TagList": [
        {
            "Key": "Department",
            "Value": "Finance"
        }
    ]
}
```
For more information, see [Tag WorkSpaces resources](https://docs.aws.amazon.com/workspaces/latest/adminguide/tag-workspaces-resources.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-tags.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This Sample fetches tag for the given Workspace**  

```
Get-WKSTag -WorkspaceId ws-w361s234r -Region us-west-2
```
**Output:**  

```
Key         Value
---         -----
auto-delete no
purpose     Workbench
```
+  For API details, see [DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This Sample fetches tag for the given Workspace**  

```
Get-WKSTag -WorkspaceId ws-w361s234r -Region us-west-2
```
**Output:**  

```
Key         Value
---         -----
auto-delete no
purpose     Workbench
```
+  For API details, see [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `DescribeWorkspaceBundles` with a CLI
<a name="workspaces_example_workspaces_DescribeWorkspaceBundles_section"></a>

The following code examples show how to use `DescribeWorkspaceBundles`.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: 
+  [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**To list the bundles provided by Amazon**  
The following `describe-workspace-bundles` example lists the names and IDs of the bundles provided by Amazon, in table format and sorted by name.  

```
aws workspaces describe-workspace-bundles \
    --owner AMAZON \
    --query "Bundles[*].[Name, BundleId]"
```
Output:  

```
[
    [
        "Standard with Amazon Linux 2",
        "wsb-clj85qzj1"
    ],
    [
        "Performance with Windows 10 (Server 2016 based)",
        "wsb-gm4d5tx2v"
    ],
    [
        "PowerPro with Windows 7",
        "wsb-1pzkp0bx4"
    ],
    [
        "Power with Amazon Linux 2",
        "wsb-2bs6k5lgn"
    ],
    [
        "Graphics with Windows 10 (Server 2019 based)",
        "wsb-03gyjnfyy"
    ],
    ...
]
```
For more information, see [WorkSpaces bundles and images](https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces-bundles.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [DescribeWorkspaceBundles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspace-bundles.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This sample fetches details of all the Workspace bundles in the current region**  

```
Get-WKSWorkspaceBundle
```
**Output:**  

```
BundleId        : wsb-sfhdgv342
ComputeType     : Amazon.WorkSpaces.Model.ComputeType
Description     : This bundle is custom
ImageId         : wsi-235aeqges
LastUpdatedTime : 12/26/2019 06:44:07
Name            : CustomBundleTest
Owner           : 233816212345
RootStorage     : Amazon.WorkSpaces.Model.RootStorage
UserStorage     : Amazon.WorkSpaces.Model.UserStorage
```
+  For API details, see [DescribeWorkspaceBundles](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This sample fetches details of all the Workspace bundles in the current region**  

```
Get-WKSWorkspaceBundle
```
**Output:**  

```
BundleId        : wsb-sfhdgv342
ComputeType     : Amazon.WorkSpaces.Model.ComputeType
Description     : This bundle is custom
ImageId         : wsi-235aeqges
LastUpdatedTime : 12/26/2019 06:44:07
Name            : CustomBundleTest
Owner           : 233816212345
RootStorage     : Amazon.WorkSpaces.Model.RootStorage
UserStorage     : Amazon.WorkSpaces.Model.UserStorage
```
+  For API details, see [DescribeWorkspaceBundles](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `DescribeWorkspaceDirectories` with a CLI
<a name="workspaces_example_workspaces_DescribeWorkspaceDirectories_section"></a>

The following code examples show how to use `DescribeWorkspaceDirectories`.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: 
+  [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**To describe a registered directory**  
The following `describe-workspace-directories` example describes the specified registered directory.  

```
aws workspaces describe-workspace-directories \
    --directory-ids d-926722edaf
```
Output:  

```
{
    "Directories": [
        {
            "DirectoryId": "d-926722edaf",
            "Alias": "d-926722edaf",
            "DirectoryName": "example.com",
            "RegistrationCode": "WSpdx+9RJ8JT",
            "SubnetIds": [
                "subnet-9d19c4c6",
                "subnet-500d5819"
            ],
            "DnsIpAddresses": [
                "172.16.1.140",
                "172.16.0.30"
            ],
            "CustomerUserName": "Administrator",
            "IamRoleId": "arn:aws:iam::123456789012:role/workspaces_DefaultRole",
            "DirectoryType": "SIMPLE_AD",
            "WorkspaceSecurityGroupId": "sg-0d89e927e5645d7c5",
            "State": "REGISTERED",
            "WorkspaceCreationProperties": {
                "EnableInternetAccess": false,
                "UserEnabledAsLocalAdministrator": true,
                "EnableMaintenanceMode": true
            },
            "WorkspaceAccessProperties": {
                "DeviceTypeWindows": "ALLOW",
                "DeviceTypeOsx": "ALLOW",
                "DeviceTypeWeb": "DENY",
                "DeviceTypeIos": "ALLOW",
                "DeviceTypeAndroid": "ALLOW",
                "DeviceTypeChromeOs": "ALLOW",
                "DeviceTypeZeroClient": "ALLOW",
                "DeviceTypeLinux": "DENY"
            },
            "Tenancy": "SHARED",
            "SelfservicePermissions": {
                "RestartWorkspace": "ENABLED",
                "IncreaseVolumeSize": "DISABLED",
                "ChangeComputeType": "DISABLED",
                "SwitchRunningMode": "DISABLED",
                "RebuildWorkspace": "DISABLED"
            }
        }
    ]
}
```
For more information, see [Manage directories for WorkSpaces Personal](https://docs.aws.amazon.com/workspaces/latest/adminguide/manage-workspaces-directory.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [DescribeWorkspaceDirectories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspace-directories.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This sample lists the directory details for registered directories**  

```
Get-WKSWorkspaceDirectory
```
**Output:**  

```
Alias                       : TestWorkspace
CustomerUserName            : Administrator
DirectoryId                 : d-123414a369
DirectoryName               : TestDirectory.com
DirectoryType               : MicrosoftAD
DnsIpAddresses              : {172.31.43.45, 172.31.2.97}
IamRoleId                   : arn:aws:iam::761234567801:role/workspaces_RoleDefault
IpGroupIds                  : {}
RegistrationCode            : WSpdx+4RRT43
SelfservicePermissions      : Amazon.WorkSpaces.Model.SelfservicePermissions
State                       : REGISTERED
SubnetIds                   : {subnet-1m3m7b43, subnet-ard11aba}
Tenancy                     : SHARED
WorkspaceAccessProperties   : Amazon.WorkSpaces.Model.WorkspaceAccessProperties
WorkspaceCreationProperties : Amazon.WorkSpaces.Model.DefaultWorkspaceCreationProperties
WorkspaceSecurityGroupId    : sg-0ed2441234a123c43
```
+  For API details, see [DescribeWorkspaceDirectories](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This sample lists the directory details for registered directories**  

```
Get-WKSWorkspaceDirectory
```
**Output:**  

```
Alias                       : TestWorkspace
CustomerUserName            : Administrator
DirectoryId                 : d-123414a369
DirectoryName               : TestDirectory.com
DirectoryType               : MicrosoftAD
DnsIpAddresses              : {172.31.43.45, 172.31.2.97}
IamRoleId                   : arn:aws:iam::761234567801:role/workspaces_RoleDefault
IpGroupIds                  : {}
RegistrationCode            : WSpdx+4RRT43
SelfservicePermissions      : Amazon.WorkSpaces.Model.SelfservicePermissions
State                       : REGISTERED
SubnetIds                   : {subnet-1m3m7b43, subnet-ard11aba}
Tenancy                     : SHARED
WorkspaceAccessProperties   : Amazon.WorkSpaces.Model.WorkspaceAccessProperties
WorkspaceCreationProperties : Amazon.WorkSpaces.Model.DefaultWorkspaceCreationProperties
WorkspaceSecurityGroupId    : sg-0ed2441234a123c43
```
+  For API details, see [DescribeWorkspaceDirectories](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `DescribeWorkspaces` with a CLI
<a name="workspaces_example_workspaces_DescribeWorkspaces_section"></a>

The following code examples show how to use `DescribeWorkspaces`.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: 
+  [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**To describe a WorkSpace**  
The following `describe-workspaces` example describes the specified WorkSpace.  

```
aws workspaces describe-workspaces \
    --workspace-ids ws-dk1xzr417
```
Output:  

```
{
    "Workspaces": [
        {
            "WorkspaceId": "ws-dk1xzr417",
            "DirectoryId": "d-926722edaf",
            "UserName": "Mary",
            "IpAddress": "172.16.0.175",
            "State": "STOPPED",
            "BundleId": "wsb-0zsvgp8fc",
            "SubnetId": "subnet-500d5819",
            "ComputerName": "WSAMZN-RBSLTTD9",
            "WorkspaceProperties": {
                "RunningMode": "AUTO_STOP",
                "RunningModeAutoStopTimeoutInMinutes": 60,
                "RootVolumeSizeGib": 80,
                "UserVolumeSizeGib": 10,
                "ComputeTypeName": "VALUE"
            },
            "ModificationStates": []
        }
    ]
}
```
For more information, see [Administer your WorkSpaces](https://docs.aws.amazon.com/workspaces/latest/adminguide/administer-workspaces.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [DescribeWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspaces.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Retrieves details of all your WorkSpaces to the pipeline.**  

```
Get-WKSWorkspace
```
**Output:**  

```
BundleId                    : wsb-1a2b3c4d
ComputerName                :
DirectoryId                 : d-1a2b3c4d
ErrorCode                   :
ErrorMessage                :
IpAddress                   :
RootVolumeEncryptionEnabled : False
State                       : PENDING
SubnetId                    :
UserName                    : myuser
UserVolumeEncryptionEnabled : False
VolumeEncryptionKey         :
WorkspaceId                 : ws-1a2b3c4d
WorkspaceProperties         : Amazon.WorkSpaces.Model.WorkspaceProperties
```
**Example 2: This command shows the values of child properties of `WorkSpaceProperties` for a workspace in the `us-west-2` region. For more information about the child properties of `WorkSpaceProperties`, see https://docs.aws.amazon.com/workspaces/latest/api/API\$1WorkspaceProperties.html.**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties
```
**Output:**  

```
        ComputeTypeName                     : STANDARD
        RootVolumeSizeGib                   : 80
        RunningMode                         : AUTO_STOP
        RunningModeAutoStopTimeoutInMinutes : 60
        UserVolumeSizeGib                   : 50
```
**Example 3: This command shows the value of the child property `RootVolumeSizeGib` of `WorkSpaceProperties` for a workspace in the `us-west-2` region. The root volume size, in GiB, is 80.**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties.RootVolumeSizeGib
```
**Output:**  

```
        80
```
+  For API details, see [DescribeWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Retrieves details of all your WorkSpaces to the pipeline.**  

```
Get-WKSWorkspace
```
**Output:**  

```
BundleId                    : wsb-1a2b3c4d
ComputerName                :
DirectoryId                 : d-1a2b3c4d
ErrorCode                   :
ErrorMessage                :
IpAddress                   :
RootVolumeEncryptionEnabled : False
State                       : PENDING
SubnetId                    :
UserName                    : myuser
UserVolumeEncryptionEnabled : False
VolumeEncryptionKey         :
WorkspaceId                 : ws-1a2b3c4d
WorkspaceProperties         : Amazon.WorkSpaces.Model.WorkspaceProperties
```
**Example 2: This command shows the values of child properties of `WorkSpaceProperties` for a workspace in the `us-west-2` region. For more information about the child properties of `WorkSpaceProperties`, see https://docs.aws.amazon.com/workspaces/latest/api/API\$1WorkspaceProperties.html.**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties
```
**Output:**  

```
        ComputeTypeName                     : STANDARD
        RootVolumeSizeGib                   : 80
        RunningMode                         : AUTO_STOP
        RunningModeAutoStopTimeoutInMinutes : 60
        UserVolumeSizeGib                   : 50
```
**Example 3: This command shows the value of the child property `RootVolumeSizeGib` of `WorkSpaceProperties` for a workspace in the `us-west-2` region. The root volume size, in GiB, is 80.**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties.RootVolumeSizeGib
```
**Output:**  

```
        80
```
+  For API details, see [DescribeWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `DescribeWorkspacesConnectionStatus` with a CLI
<a name="workspaces_example_workspaces_DescribeWorkspacesConnectionStatus_section"></a>

The following code examples show how to use `DescribeWorkspacesConnectionStatus`.

------
#### [ CLI ]

**AWS CLI**  
**To describe the connection status of a WorkSpace**  
The following `describe-workspaces-connection-status` example describes the connection status of the specified WorkSpace.  

```
aws workspaces describe-workspaces-connection-status \
    --workspace-ids ws-dk1xzr417
```
Output:  

```
{
    "WorkspacesConnectionStatus": [
        {
            "WorkspaceId": "ws-dk1xzr417",
            "ConnectionState": "CONNECTED",
            "ConnectionStateCheckTimestamp": 1662526214.744
        }
    ]
}
```
For more information, see [Administer your WorkSpaces](https://docs.aws.amazon.com/workspaces/latest/adminguide/administer-workspaces.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [DescribeWorkspacesConnectionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspaces-connection-status.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This sample fetches the connection status for the specified Workspace**  

```
Get-WKSWorkspacesConnectionStatus -WorkspaceId ws-w123s234r
```
+  For API details, see [DescribeWorkspacesConnectionStatus](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This sample fetches the connection status for the specified Workspace**  

```
Get-WKSWorkspacesConnectionStatus -WorkspaceId ws-w123s234r
```
+  For API details, see [DescribeWorkspacesConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `ModifyWorkspaceCreationProperties` with a CLI
<a name="workspaces_example_workspaces_ModifyWorkspaceCreationProperties_section"></a>

The following code examples show how to use `ModifyWorkspaceCreationProperties`.

------
#### [ CLI ]

**AWS CLI**  
**To modify a WorkSpace creation property of a directory**  
The following `modify-workspace-creation-properties` example enables the `EnableInternetAccess` property for the specified directory. This enables automatic assignment of public IP addresses for the WorkSpaces created for the directory.  

```
aws workspaces modify-workspace-creation-properties \
    --resource-id d-926722edaf \
    --workspace-creation-properties EnableInternetAccess=true
```
This command produces no output.  
For more information, see [Update directory details for your WorkSpaces](https://docs.aws.amazon.com/workspaces/latest/adminguide/update-directory-details.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [ModifyWorkspaceCreationProperties](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/modify-workspace-creation-properties.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This sample enables Internet Access and Maintenance Mode to true as default values while creating a Workspace**  

```
Edit-WKSWorkspaceCreationProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceCreationProperties_EnableInternetAccess $true -WorkspaceCreationProperties_EnableMaintenanceMode $true
```
+  For API details, see [ModifyWorkspaceCreationProperties](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This sample enables Internet Access and Maintenance Mode to true as default values while creating a Workspace**  

```
Edit-WKSWorkspaceCreationProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceCreationProperties_EnableInternetAccess $true -WorkspaceCreationProperties_EnableMaintenanceMode $true
```
+  For API details, see [ModifyWorkspaceCreationProperties](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `ModifyWorkspaceProperties` with a CLI
<a name="workspaces_example_workspaces_ModifyWorkspaceProperties_section"></a>

The following code examples show how to use `ModifyWorkspaceProperties`.

------
#### [ CLI ]

**AWS CLI**  
**To modify the running mode of a WorkSpace**  
The following `modify-workspace-properties` example sets the running mode of the specified WorkSpace to `AUTO_STOP`.  

```
aws workspaces modify-workspace-properties \
    --workspace-id ws-dk1xzr417 \
    --workspace-properties RunningMode=AUTO_STOP
```
This command produces no output.  
For more information, see [Modify a WorkSpace](https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [ModifyWorkspaceProperties](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/modify-workspace-properties.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This Sample changes the Workspace Running Mode Property to Auto Stop for the specified Workspace**  

```
Edit-WKSWorkspaceProperty -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceProperties_RunningMode AUTO_STOP
```
+  For API details, see [ModifyWorkspaceProperties](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This Sample changes the Workspace Running Mode Property to Auto Stop for the specified Workspace**  

```
Edit-WKSWorkspaceProperty -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceProperties_RunningMode AUTO_STOP
```
+  For API details, see [ModifyWorkspaceProperties](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `ModifyWorkspaceState` with a CLI
<a name="workspaces_example_workspaces_ModifyWorkspaceState_section"></a>

The following code examples show how to use `ModifyWorkspaceState`.

------
#### [ CLI ]

**AWS CLI**  
**To modify the state of a WorkSpace**  
The following `modify-workspace-state` example sets the state of the specified WorkSpace to `ADMIN_MAINTENANCE`.  

```
aws workspaces modify-workspace-state \
    --workspace-id ws-dk1xzr417 \
    --workspace-state ADMIN_MAINTENANCE
```
This command produces no output.  
For more information, see [WorkSpace maintenance](https://docs.aws.amazon.com/workspaces/latest/adminguide/workspace-maintenance.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [ModifyWorkspaceState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/modify-workspace-state.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This sample changes the state of the specified Workspace to Available**  

```
Edit-WKSWorkspaceState -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceState AVAILABLE
```
+  For API details, see [ModifyWorkspaceState](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This sample changes the state of the specified Workspace to Available**  

```
Edit-WKSWorkspaceState -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceState AVAILABLE
```
+  For API details, see [ModifyWorkspaceState](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `RebootWorkspaces` with a CLI
<a name="workspaces_example_workspaces_RebootWorkspaces_section"></a>

The following code examples show how to use `RebootWorkspaces`.

------
#### [ CLI ]

**AWS CLI**  
**To reboot a WorkSpace**  
The following `reboot-workspaces` example reboots the specified WorkSpace.  

```
aws workspaces reboot-workspaces \
    --reboot-workspace-requests ws-dk1xzr417
```
Output:  

```
{
    "FailedRequests": []
}
```
For more information, see [Reboot a WorkSpace](https://docs.aws.amazon.com/workspaces/latest/adminguide/reboot-workspaces.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [RebootWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/reboot-workspaces.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Reboots the specified WorkSpace.**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**Example 2: Reboots multiple WorkSpaces.**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d","ws-5a6b7c8d"
```
**Example 3: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Restart-WKSWorkspace, causing the WorkSpaces to be restarted.**  

```
Get-WKSWorkspaces | Restart-WKSWorkspace
```
+  For API details, see [RebootWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Reboots the specified WorkSpace.**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**Example 2: Reboots multiple WorkSpaces.**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d","ws-5a6b7c8d"
```
**Example 3: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Restart-WKSWorkspace, causing the WorkSpaces to be restarted.**  

```
Get-WKSWorkspaces | Restart-WKSWorkspace
```
+  For API details, see [RebootWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `RebuildWorkspaces` with a CLI
<a name="workspaces_example_workspaces_RebuildWorkspaces_section"></a>

The following code examples show how to use `RebuildWorkspaces`.

------
#### [ CLI ]

**AWS CLI**  
**To rebuild a WorkSpace**  
The following `rebuild-workspaces` example rebuilds the specified WorkSpace.  

```
aws workspaces rebuild-workspaces \
    --rebuild-workspace-requests ws-dk1xzr417
```
Output:  

```
{
    "FailedRequests": []
}
```
For more information, see [Rebuild a WorkSpace](https://docs.aws.amazon.com/workspaces/latest/adminguide/rebuild-workspace.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [RebuildWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/rebuild-workspaces.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Rebuilds the specified WorkSpace.**  

```
Reset-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**Example 2: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Reset-WKSWorkspace, causing the WorkSpaces to be rebuilt.**  

```
Get-WKSWorkspaces | Reset-WKSWorkspace
```
+  For API details, see [RebuildWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Rebuilds the specified WorkSpace.**  

```
Reset-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**Example 2: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Reset-WKSWorkspace, causing the WorkSpaces to be rebuilt.**  

```
Get-WKSWorkspaces | Reset-WKSWorkspace
```
+  For API details, see [RebuildWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `RegisterWorkspaceDirectory` with a CLI
<a name="workspaces_example_workspaces_RegisterWorkspaceDirectory_section"></a>

The following code examples show how to use `RegisterWorkspaceDirectory`.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: 
+  [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**To register a directory**  
The following `register-workspace-directory` example registers the specified directory for use with Amazon WorkSpaces.  

```
aws workspaces register-workspace-directory \
    --directory-id d-926722edaf
```
This command produces no output.  
For more information, see [Register an existing AWS Directory Service directory with WorkSpaces Personal](https://docs.aws.amazon.com/workspaces/latest/adminguide/register-deregister-directory.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [RegisterWorkspaceDirectory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/register-workspace-directory.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: This sample registers the specified directory for Workspaces Service**  

```
Register-WKSWorkspaceDirectory -DirectoryId d-123412a123 -EnableWorkDoc $false
```
+  For API details, see [RegisterWorkspaceDirectory](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: This sample registers the specified directory for Workspaces Service**  

```
Register-WKSWorkspaceDirectory -DirectoryId d-123412a123 -EnableWorkDoc $false
```
+  For API details, see [RegisterWorkspaceDirectory](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `StopWorkspaces` with a CLI
<a name="workspaces_example_workspaces_StopWorkspaces_section"></a>

The following code examples show how to use `StopWorkspaces`.

------
#### [ CLI ]

**AWS CLI**  
**To stop an AutoStop WorkSpace**  
The following `stop-workspaces` example stops the specified WorkSpace. The WorkSpace must have a running mode of `AutoStop`.  

```
aws workspaces stop-workspaces \
    --stop-workspace-requests WorkspaceId=ws-dk1xzr417
```
Output:  

```
{
    "FailedRequests": []
}
```
For more information, see [Stop and start an AutoStop WorkSpace](https://docs.aws.amazon.com/workspaces/latest/adminguide/running-mode.html#stop-start-workspace) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [StopWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/stop-workspaces.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Stops multiple WorkSpaces.**  

```
Stop-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0"
```
**Example 2: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Stop-WKSWorkspace causing the WorkSpaces to be stopped.**  

```
Get-WKSWorkspaces | Stop-WKSWorkspace
```
**Example 3: This example shows how to pass StopRequest objects defining the WorkSpaces to be stopped.**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Stop-WKSWorkspace -Request $arrRequest
```
+  For API details, see [StopWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Stops multiple WorkSpaces.**  

```
Stop-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0"
```
**Example 2: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Stop-WKSWorkspace causing the WorkSpaces to be stopped.**  

```
Get-WKSWorkspaces | Stop-WKSWorkspace
```
**Example 3: This example shows how to pass StopRequest objects defining the WorkSpaces to be stopped.**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Stop-WKSWorkspace -Request $arrRequest
```
+  For API details, see [StopWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `TerminateWorkspaces` with a CLI
<a name="workspaces_example_workspaces_TerminateWorkspaces_section"></a>

The following code examples show how to use `TerminateWorkspaces`.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: 
+  [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**To terminate a WorkSpace**  
The following `terminate-workspaces` example terminates the specified workspace.  

```
aws workspaces terminate-workspaces \
    --terminate-workspace-requests ws-dk1xzr417
```
Output:  

```
{
    "FailedRequests": []
}
```
For more information, see [Delete a WorkSpace](https://docs.aws.amazon.com/workspaces/latest/adminguide/delete-workspaces.html) in the *Amazon WorkSpaces Administration Guide*.  
+  For API details, see [TerminateWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/terminate-workspaces.html) in *AWS CLI Command Reference*. 

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**Example 1: Terminates multiple WorkSpaces. use of the -Force switch stops the cmdlet from prompting for confirmation.**  

```
Remove-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0" -Force
```
**Example 2: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Remove-WKSWorkspace, terminating all of the WorkSpaces. The cmdlet will prompt before each WorkSpace is terminated. To suppress the confirmation prompt add the -Force switch.**  

```
Get-WKSWorkspaces | Remove-WKSWorkspace
```
**Example 3: This example shows how to pass TerminateRequest objects defining the WorkSpaces to be terminated. The cmdlet will prompt for confirmation before proceeding, unless the -Force switch parameter is also specified.**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Remove-WKSWorkspace -Request $arrRequest
```
+  For API details, see [TerminateWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Terminates multiple WorkSpaces. use of the -Force switch stops the cmdlet from prompting for confirmation.**  

```
Remove-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0" -Force
```
**Example 2: Retrieves the collection of all your WorkSpaces and pipes the IDs to the -WorkSpaceId parameter of Remove-WKSWorkspace, terminating all of the WorkSpaces. The cmdlet will prompt before each WorkSpace is terminated. To suppress the confirmation prompt add the -Force switch.**  

```
Get-WKSWorkspaces | Remove-WKSWorkspace
```
**Example 3: This example shows how to pass TerminateRequest objects defining the WorkSpaces to be terminated. The cmdlet will prompt for confirmation before proceeding, unless the -Force switch parameter is also specified.**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Remove-WKSWorkspace -Request $arrRequest
```
+  For API details, see [TerminateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Scenarios for WorkSpaces using AWS SDKs
<a name="workspaces_code_examples_scenarios"></a>

The following code examples show you how to implement common scenarios in WorkSpaces with AWS SDKs. These scenarios show you how to accomplish specific tasks by calling multiple functions within WorkSpaces or combined with other AWS services. Each scenario includes a link to the complete source code, where you can find instructions on how to set up and run the code. 

Scenarios target an intermediate level of experience to help you understand service actions in context.

**Topics**
+ [Creating and managing Amazon WorkSpaces Personal](workspaces_example_workspaces_GettingStarted_035_section.md)

# Creating and managing Amazon WorkSpaces Personal
<a name="workspaces_example_workspaces_GettingStarted_035_section"></a>

The following code example shows how to:
+ Verify WorkSpaces availability in your region
+ List available WorkSpaces bundles
+ Create a WorkSpace
+ Check the status of your WorkSpace
+ Clean up resources

------
#### [ Bash ]

**AWS CLI with Bash script**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Sample developer tutorials](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/035-workspaces-personal) repository. 

```
#!/bin/bash

# Script to create a WorkSpace in WorkSpaces Personal
# This script follows the workflow described in the AWS documentation
# https://docs.aws.amazon.com/workspaces/latest/adminguide/create-workspaces-personal.html

# Set up logging
LOG_FILE="workspaces_creation.log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "$(date): Starting WorkSpaces creation script"
echo "=============================================="

# Initialize resource tracking array
declare -a CREATED_RESOURCES

# Function to handle errors
handle_error() {
    echo "ERROR: $1"
    echo "Resources created before error:"
    for resource in "${CREATED_RESOURCES[@]}"; do
        echo "  - $resource"
    done
    exit 1
}

# Function to check if a command succeeded
check_command() {
    # Check for ResourceNotFound.User error specifically
    if echo "$1" | grep -q "ResourceNotFound.User"; then
        echo ""
        echo "ERROR: User not found in the directory."
        echo ""
        echo "This error occurs when the specified username doesn't exist in the directory."
        echo ""
        echo "To resolve this issue:"
        echo "1. Ensure the user exists in the directory before creating a WorkSpace."
        echo "2. For Simple AD and AWS Managed Microsoft AD:"
        echo "   - Connect to a directory-joined instance"
        echo "   - Use Active Directory tools to create the user"
        echo "   - See: https://docs.aws.amazon.com/workspaces/latest/adminguide/manage-users.html"
        echo ""
        echo "3. For AD Connector:"
        echo "   - Create the user in your on-premises Active Directory"
        echo "   - Ensure proper synchronization with the AD Connector"
        echo ""
        echo "4. Alternatively, you can use the AWS Console to create a WorkSpace,"
        echo "   which can create the user automatically in some directory types."
        echo ""
        handle_error "User '$USERNAME' not found in directory '$DIRECTORY_ID'"
    # Check for other errors
    elif echo "$1" | grep -i "error" > /dev/null; then
        handle_error "$1"
    fi
}

# Step 0: Select AWS region
echo ""
echo "=============================================="
echo "AWS REGION SELECTION"
echo "=============================================="
echo "Enter the AWS region to use (e.g., us-east-1, us-west-2):"
read -r AWS_REGION

if [ -z "$AWS_REGION" ]; then
    handle_error "Region cannot be empty"
fi

export AWS_DEFAULT_REGION="$AWS_REGION"
echo "Using AWS region: $AWS_REGION"

# Step 1: Prompt for directory ID
echo ""
echo "=============================================="
echo "DIRECTORY SELECTION"
echo "=============================================="
echo "Listing available directories..."

DIRECTORIES_OUTPUT=$(aws workspaces describe-workspace-directories --output json)
check_command "$DIRECTORIES_OUTPUT"
echo "$DIRECTORIES_OUTPUT"

# Extract directory IDs and display them
DIRECTORY_IDS=$(echo "$DIRECTORIES_OUTPUT" | grep -o '"DirectoryId": "[^"]*' | cut -d'"' -f4)

if [ -z "$DIRECTORY_IDS" ]; then
    echo "No directories found. Please create a directory first using AWS Directory Service."
    echo "For more information, see: https://docs.aws.amazon.com/workspaces/latest/adminguide/register-deregister-directory.html"
    exit 1
fi

echo ""
echo "Available directory IDs:"
echo "$DIRECTORY_IDS"
echo ""
echo "Enter the directory ID you want to use:"
read -r DIRECTORY_ID

# Validate directory ID
if ! echo "$DIRECTORY_IDS" | grep -q "$DIRECTORY_ID"; then
    echo "Directory ID $DIRECTORY_ID not found in the list of available directories."
    echo "Please check the ID and try again."
    exit 1
fi

echo "Selected directory ID: $DIRECTORY_ID"

# Step 2: Check if directory is registered with WorkSpaces
echo ""
echo "=============================================="
echo "CHECKING DIRECTORY REGISTRATION"
echo "=============================================="

REGISTERED=$(echo "$DIRECTORIES_OUTPUT" | grep -A 5 "\"DirectoryId\": \"$DIRECTORY_ID\"" | grep -c "\"State\": \"REGISTERED\"")

if [ "$REGISTERED" -eq 0 ]; then
    echo "Directory $DIRECTORY_ID is not registered with WorkSpaces. Registering now..."
    REGISTER_OUTPUT=$(aws workspaces register-workspace-directory --directory-id "$DIRECTORY_ID")
    check_command "$REGISTER_OUTPUT"
    echo "Directory registration initiated. This may take a few minutes."
    
    # Add to resource tracking
    CREATED_RESOURCES+=("Directory registration: $DIRECTORY_ID")
    
    # Wait for directory to be registered
    echo "Waiting for directory registration to complete..."
    sleep 30
    
    # Check registration status
    REGISTRATION_CHECK=$(aws workspaces describe-workspace-directories --directory-ids "$DIRECTORY_ID")
    check_command "$REGISTRATION_CHECK"
    
    REGISTRATION_STATE=$(echo "$REGISTRATION_CHECK" | grep -o '"State": "[^"]*' | cut -d'"' -f4)
    if [ "$REGISTRATION_STATE" != "REGISTERED" ]; then
        echo "Directory registration is still in progress. Current state: $REGISTRATION_STATE"
        echo "Please check the AWS console for the final status."
        echo "You may need to wait a few minutes before proceeding."
    else
        echo "Directory successfully registered with WorkSpaces."
    fi
else
    echo "Directory $DIRECTORY_ID is already registered with WorkSpaces."
fi

# Get directory type to provide appropriate user guidance
DIRECTORY_TYPE=$(echo "$DIRECTORIES_OUTPUT" | grep -A 10 "\"DirectoryId\": \"$DIRECTORY_ID\"" | grep -o '"DirectoryType": "[^"]*' | cut -d'"' -f4)
echo "Directory type: $DIRECTORY_TYPE"

# Display user creation guidance based on directory type
echo ""
echo "=============================================="
echo "USER CREATION GUIDANCE"
echo "=============================================="
case "$DIRECTORY_TYPE" in
    "SimpleAD" | "MicrosoftAD")
        echo "For $DIRECTORY_TYPE, users must be created using Active Directory tools."
        echo "1. Connect to a directory-joined EC2 instance"
        echo "2. Use Active Directory Users and Computers to create users"
        echo "3. For detailed instructions, see: https://docs.aws.amazon.com/workspaces/latest/adminguide/manage-users.html"
        ;;
    "ADConnector")
        echo "For AD Connector, users must exist in your on-premises Active Directory."
        echo "1. Create the user in your on-premises Active Directory"
        echo "2. Ensure the user is in an OU that is within the scope of your AD Connector"
        echo "3. For detailed instructions, see: https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ad_connector_management.html"
        ;;
    *)
        echo "For this directory type, ensure users exist before creating WorkSpaces."
        echo "For detailed instructions, see: https://docs.aws.amazon.com/workspaces/latest/adminguide/manage-users.html"
        ;;
esac
echo ""

# Step 3: List available bundles
echo ""
echo "=============================================="
echo "BUNDLE SELECTION"
echo "=============================================="
echo "Listing available WorkSpace bundles..."

# Get bundles with a format that's easier to parse
BUNDLES_OUTPUT=$(aws workspaces describe-workspace-bundles --owner AMAZON --output text --query "Bundles[*].[BundleId,Name,ComputeType.Name,RootStorage.Capacity,UserStorage.Capacity]")
check_command "$BUNDLES_OUTPUT"

# Extract bundle information and display in a numbered list
echo "Available bundles:"
echo "-----------------"
echo "NUM | BUNDLE ID | NAME | COMPUTE TYPE | ROOT STORAGE | USER STORAGE"
echo "-----------------------------------------------------------------"

# Create arrays to store bundle information
declare -a BUNDLE_IDS
declare -a BUNDLE_NAMES

# Process the output to extract bundle information
COUNT=1
while IFS=$'\t' read -r BUNDLE_ID BUNDLE_NAME COMPUTE_TYPE ROOT_STORAGE USER_STORAGE || [[ -n "$BUNDLE_ID" ]]; do
    # Store in arrays
    BUNDLE_IDS[$COUNT]="$BUNDLE_ID"
    BUNDLE_NAMES[$COUNT]="$BUNDLE_NAME"
    
    # Display with number
    echo "$COUNT | $BUNDLE_ID | $BUNDLE_NAME | $COMPUTE_TYPE | $ROOT_STORAGE GB | $USER_STORAGE GB"
    
    ((COUNT++))
done <<< "$BUNDLES_OUTPUT"

# Prompt for selection
echo ""
echo "Enter the number of the bundle you want to use (1-$((COUNT-1))):"
read -r BUNDLE_SELECTION

# Validate selection
if ! [[ "$BUNDLE_SELECTION" =~ ^[0-9]+$ ]] || [ "$BUNDLE_SELECTION" -lt 1 ] || [ "$BUNDLE_SELECTION" -ge "$COUNT" ]; then
    handle_error "Invalid bundle selection. Please enter a number between 1 and $((COUNT-1))."
fi

# Get the selected bundle ID
BUNDLE_ID="${BUNDLE_IDS[$BUNDLE_SELECTION]}"
BUNDLE_NAME="${BUNDLE_NAMES[$BUNDLE_SELECTION]}"

echo "Selected bundle: $BUNDLE_NAME (ID: $BUNDLE_ID)"

# Step 4: Prompt for username
echo ""
echo "=============================================="
echo "USER INFORMATION"
echo "=============================================="
echo "Enter the username for the WorkSpace:"
read -r USERNAME

echo "NOTE: The user must already exist in the directory for the WorkSpace creation to succeed."
echo "If you're using Simple AD or AWS Managed Microsoft AD, the user must be created using Active Directory tools."
echo "If you're using AD Connector, the user must exist in your on-premises Active Directory."
echo ""

echo "Enter the user's first name:"
read -r FIRST_NAME

echo "Enter the user's last name:"
read -r LAST_NAME

echo "Enter the user's email address:"
read -r EMAIL

# Step 5: Choose running mode
echo ""
echo "=============================================="
echo "RUNNING MODE SELECTION"
echo "=============================================="
echo "Select running mode:"
echo "1. AlwaysOn (billed monthly)"
echo "2. AutoStop (billed hourly)"
read -r RUNNING_MODE_CHOICE

if [ "$RUNNING_MODE_CHOICE" = "1" ]; then
    RUNNING_MODE="ALWAYS_ON"
    AUTO_STOP_TIMEOUT=""
else
    RUNNING_MODE="AUTO_STOP"
    AUTO_STOP_TIMEOUT=60
fi

echo "Selected running mode: $RUNNING_MODE"

# Step 6: Add tags (optional)
echo ""
echo "=============================================="
echo "TAGS (OPTIONAL)"
echo "=============================================="
echo "Would you like to add tags to your WorkSpace? (y/n):"
read -r ADD_TAGS

TAGS_JSON=""
if [ "$ADD_TAGS" = "y" ] || [ "$ADD_TAGS" = "Y" ]; then
    echo "Enter tag key (e.g., Department):"
    read -r TAG_KEY
    
    echo "Enter tag value (e.g., IT):"
    read -r TAG_VALUE
    
    TAGS_JSON="[{\"Key\":\"$TAG_KEY\",\"Value\":\"$TAG_VALUE\"}]"
fi

# Step 7: Create the WorkSpace
echo ""
echo "=============================================="
echo "CREATING WORKSPACE"
echo "=============================================="
echo "Creating WorkSpace with the following parameters:"
echo "Directory ID: $DIRECTORY_ID"
echo "Username: $USERNAME"
echo "Bundle ID: $BUNDLE_ID"
echo "Running Mode: $RUNNING_MODE"
if [ -n "$TAGS_JSON" ]; then
    echo "Tags: $TAG_KEY=$TAG_VALUE"
fi

# Create JSON for workspace properties
if [ "$RUNNING_MODE" = "AUTO_STOP" ]; then
    PROPERTIES_JSON="{\"RunningMode\":\"$RUNNING_MODE\",\"RunningModeAutoStopTimeoutInMinutes\":$AUTO_STOP_TIMEOUT}"
else
    PROPERTIES_JSON="{\"RunningMode\":\"$RUNNING_MODE\"}"
fi

# Create JSON for workspaces parameter
WORKSPACE_JSON="{\"DirectoryId\":\"$DIRECTORY_ID\",\"UserName\":\"$USERNAME\",\"BundleId\":\"$BUNDLE_ID\",\"WorkspaceProperties\":$PROPERTIES_JSON"

# Add tags if specified
if [ -n "$TAGS_JSON" ]; then
    WORKSPACE_JSON="$WORKSPACE_JSON,\"Tags\":$TAGS_JSON"
fi

# Close the JSON object
WORKSPACE_JSON="$WORKSPACE_JSON}"

# Construct the create-workspaces command
CREATE_COMMAND="aws workspaces create-workspaces --workspaces '$WORKSPACE_JSON'"

echo "Executing: $CREATE_COMMAND"
CREATE_OUTPUT=$(eval "$CREATE_COMMAND")
check_command "$CREATE_OUTPUT"
echo "$CREATE_OUTPUT"

# Extract WorkSpace ID
WORKSPACE_ID=$(echo "$CREATE_OUTPUT" | grep -o '"WorkspaceId": "[^"]*' | head -1 | cut -d'"' -f4)

if [ -z "$WORKSPACE_ID" ]; then
    handle_error "Failed to extract WorkSpace ID from creation output."
fi

echo "WorkSpace creation initiated. WorkSpace ID: $WORKSPACE_ID"
CREATED_RESOURCES+=("WorkSpace: $WORKSPACE_ID")

# Step 8: Check WorkSpace status
echo ""
echo "=============================================="
echo "CHECKING WORKSPACE STATUS"
echo "=============================================="
echo "Checking status of WorkSpace $WORKSPACE_ID..."

# Initial status check
STATUS_OUTPUT=$(aws workspaces describe-workspaces --workspace-ids "$WORKSPACE_ID")
check_command "$STATUS_OUTPUT"
echo "$STATUS_OUTPUT"

WORKSPACE_STATE=$(echo "$STATUS_OUTPUT" | grep -o '"State": "[^"]*' | head -1 | cut -d'"' -f4)
echo "Current WorkSpace state: $WORKSPACE_STATE"

# Wait for WorkSpace to be available (this can take 20+ minutes)
echo ""
echo "WorkSpace creation is in progress. This can take 20+ minutes."
echo "The script will check the status every 60 seconds."
echo "Press Ctrl+C to exit the script at any time. The WorkSpace will continue to be created."

while [ "$WORKSPACE_STATE" = "PENDING" ]; do
    echo "$(date): WorkSpace state is still PENDING. Waiting 60 seconds before checking again..."
    sleep 60
    
    STATUS_OUTPUT=$(aws workspaces describe-workspaces --workspace-ids "$WORKSPACE_ID")
    check_command "$STATUS_OUTPUT"
    
    WORKSPACE_STATE=$(echo "$STATUS_OUTPUT" | grep -o '"State": "[^"]*' | head -1 | cut -d'"' -f4)
    echo "$(date): Current WorkSpace state: $WORKSPACE_STATE"
    
    # If state is ERROR or UNHEALTHY, exit
    if [ "$WORKSPACE_STATE" = "ERROR" ] || [ "$WORKSPACE_STATE" = "UNHEALTHY" ]; then
        handle_error "WorkSpace creation failed. Final state: $WORKSPACE_STATE"
    fi
    
    # If state is AVAILABLE, break the loop
    if [ "$WORKSPACE_STATE" = "AVAILABLE" ]; then
        break
    fi
done

# Step 9: Display WorkSpace information
echo ""
echo "=============================================="
echo "WORKSPACE CREATION COMPLETE"
echo "=============================================="
echo "WorkSpace has been successfully created!"
echo "WorkSpace ID: $WORKSPACE_ID"
echo "Directory ID: $DIRECTORY_ID"
echo "Username: $USERNAME"
echo "Running Mode: $RUNNING_MODE"

# Step 10: Remind about invitation emails
echo ""
echo "=============================================="
echo "INVITATION EMAILS"
echo "=============================================="
echo "IMPORTANT: If you're using AD Connector or a trust relationship, or if the user already exists in Active Directory,"
echo "invitation emails are not sent automatically. You'll need to manually send an invitation email."
echo "For more information, see: https://docs.aws.amazon.com/workspaces/latest/adminguide/manage-workspaces-users.html#send-invitation"

# Step 11: Cleanup confirmation
echo ""
echo "=============================================="
echo "CLEANUP CONFIRMATION"
echo "=============================================="
echo "Resources created:"
for resource in "${CREATED_RESOURCES[@]}"; do
    echo "  - $resource"
done

echo ""
echo "Do you want to clean up all created resources? (y/n):"
read -r CLEANUP_CHOICE

if [ "$CLEANUP_CHOICE" = "y" ] || [ "$CLEANUP_CHOICE" = "Y" ]; then
    echo ""
    echo "=============================================="
    echo "CLEANING UP RESOURCES"
    echo "=============================================="
    
    # Terminate WorkSpace
    if [ -n "$WORKSPACE_ID" ]; then
        echo "Terminating WorkSpace $WORKSPACE_ID..."
        TERMINATE_OUTPUT=$(aws workspaces terminate-workspaces --terminate-workspace-requests WorkspaceId="$WORKSPACE_ID")
        check_command "$TERMINATE_OUTPUT"
        echo "$TERMINATE_OUTPUT"
        echo "WorkSpace termination initiated. This may take a few minutes."
    fi
    
    # Deregister directory (only if we registered it in this script)
    if [[ " ${CREATED_RESOURCES[*]} " == *"Directory registration: $DIRECTORY_ID"* ]]; then
        echo "Deregistering directory $DIRECTORY_ID from WorkSpaces..."
        DEREGISTER_OUTPUT=$(aws workspaces deregister-workspace-directory --directory-id "$DIRECTORY_ID")
        check_command "$DEREGISTER_OUTPUT"
        echo "$DEREGISTER_OUTPUT"
        echo "Directory deregistration initiated. This may take a few minutes."
    fi
    
    echo "Cleanup completed."
else
    echo "Skipping cleanup. Resources will remain in your AWS account."
fi

echo ""
echo "=============================================="
echo "SCRIPT COMPLETED"
echo "=============================================="
echo "Log file: $LOG_FILE"
echo "Thank you for using the WorkSpaces creation script!"
```
+ For API details, see the following topics in *AWS CLI Command Reference*.
  + [CreateWorkspaces](https://docs.aws.amazon.com/goto/aws-cli/workspaces-2015-04-08/CreateWorkspaces)
  + [DeregisterWorkspaceDirectory](https://docs.aws.amazon.com/goto/aws-cli/workspaces-2015-04-08/DeregisterWorkspaceDirectory)
  + [DescribeWorkspaceBundles](https://docs.aws.amazon.com/goto/aws-cli/workspaces-2015-04-08/DescribeWorkspaceBundles)
  + [DescribeWorkspaceDirectories](https://docs.aws.amazon.com/goto/aws-cli/workspaces-2015-04-08/DescribeWorkspaceDirectories)
  + [DescribeWorkspaces](https://docs.aws.amazon.com/goto/aws-cli/workspaces-2015-04-08/DescribeWorkspaces)
  + [RegisterWorkspaceDirectory](https://docs.aws.amazon.com/goto/aws-cli/workspaces-2015-04-08/RegisterWorkspaceDirectory)
  + [TerminateWorkspaces](https://docs.aws.amazon.com/goto/aws-cli/workspaces-2015-04-08/TerminateWorkspaces)

------