

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

# `DeleteUserPolicy` 搭配 AWS SDK 或 CLI 使用
<a name="iam_example_iam_DeleteUserPolicy_section"></a>

下列程式碼範例示範如何使用 `DeleteUserPolicy`。

動作範例是大型程式的程式碼摘錄，必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作：
+  [了解基本概念](iam_example_iam_Scenario_CreateUserAssumeRole_section.md) 

------
#### [ .NET ]

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)中設定和執行。

```
    /// <summary>
    /// Delete an IAM user policy.
    /// </summary>
    /// <param name="policyName">The name of the IAM policy to delete.</param>
    /// <param name="userName">The username of the IAM user.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserPolicyAsync(string policyName, string userName)
    {
        var response = await _IAMService.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policyName, UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  如需 API 詳細資訊，請參閱 *適用於 .NET 的 AWS SDK API Reference* 中的 [DeleteUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUserPolicy)。

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

**AWS CLI**  
**從 IAM 使用者中移除政策**  
下列 `delete-user-policy` 命令會將指定的政策從名為 `Bob` 的 IAM 使用者中移除。  

```
aws iam delete-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy
```
此命令不會產生輸出。  
若要取得 IAM 使用者的政策清單，請使用 `list-user-policies` 命令。  
如需詳細資訊，請參閱《[IAM 使用者指南》中的在 AWS 帳戶中建立](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html) *AWS IAM* 使用者。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-user-policy.html)。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)中設定和執行。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// DeleteUserPolicy deletes an inline policy from a user.
func (wrapper UserWrapper) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
	_, err := wrapper.IamClient.DeleteUserPolicy(ctx, &iam.DeleteUserPolicyInput{
		PolicyName: aws.String(policyName),
		UserName:   aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete policy from user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  如需 API 詳細資訊，請參閱 *適用於 Go 的 AWS SDK API Reference* 中的 [DeleteUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUserPolicy)。

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

**Tools for PowerShell V4**  
**範例 1：此範例會刪除內嵌在名為 `Bob` 之 IAM 使用者中的、名為 `AccessToEC2Policy` 的內嵌政策。**  

```
Remove-IAMUserPolicy -PolicyName AccessToEC2Policy -UserName Bob
```
**範例 2：此範例會尋找內嵌在名為 `Theresa` 的 IAM 使用者中的所有內嵌政策，然後將其刪除。**  

```
$inlinepols = Get-IAMUserPolicies -UserName Theresa
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName Theresa -Force}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除內嵌在名為 `Bob` 之 IAM 使用者中的、名為 `AccessToEC2Policy` 的內嵌政策。**  

```
Remove-IAMUserPolicy -PolicyName AccessToEC2Policy -UserName Bob
```
**範例 2：此範例會尋找內嵌在名為 `Theresa` 的 IAM 使用者中的所有內嵌政策，然後將其刪除。**  

```
$inlinepols = Get-IAMUserPolicies -UserName Theresa
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName Theresa -Force}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)中設定和執行。

```
  # Deletes a user and their associated resources
  #
  # @param user_name [String] The name of the user to delete
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
```
+  如需 API 詳細資訊，請參閱 *適用於 Ruby 的 AWS SDK API Reference* 中的 [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUserPolicy)。

------
#### [ Rust ]

**SDK for Rust**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)中設定和執行。

```
pub async fn delete_user_policy(
    client: &iamClient,
    user: &User,
    policy_name: &str,
) -> Result<(), SdkError<DeleteUserPolicyError>> {
    client
        .delete_user_policy()
        .user_name(user.user_name())
        .policy_name(policy_name)
        .send()
        .await?;

    Ok(())
}
```
+  如需 API 詳細資訊，請參閱 *AWS SDK for Rust API reference* 中的 [DeleteUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user_policy)。

------
#### [ Swift ]

**SDK for Swift**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)中設定和執行。

```
import AWSIAM
import AWSS3


    func deleteUserPolicy(user: IAMClientTypes.User, policyName: String) async throws {
        let input = DeleteUserPolicyInput(
            policyName: policyName,
            userName: user.userName
        )
        do {
            _ = try await iamClient.deleteUserPolicy(input: input)
        } catch {
            print("ERROR: deleteUserPolicy:", dump(error))
            throw error
        }
    }
```
+  如需 API 詳細資訊，請參閱 *AWS SDK for Swift API reference* 中的 [DeleteUserPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleteuserpolicy(input:))。

------

如需 AWS SDK 開發人員指南和程式碼範例的完整清單，請參閱 [搭配 AWS SDK 使用此服務](sdk-general-information-section.md)。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。