0

我正在编写一个 powershell 模块来与 AWS 交互。大多数函数都需要接受参数,这些参数是要使用的凭据-awsAccessKeyId和.awsSecretKeycredentialsFile

将这些参数复制/粘贴到模块中的每个函数变得越来越枯燥。

有没有办法声明这些是CommonParameters用于模块导出的函数集?

另外,有没有办法提取通用(即重复的)参数集处理开关语句,以便所有需要它的函数都可以调用它?

这是一个示例函数:

function New-S3Client {
    [CmdletBinding(DefaultParametersetName="credentialsFile")]
    param
    (
        [parameter(Mandatory=$true, ParameterSetName="specifyKey")] [string]$accessKey,
        [parameter(Mandatory=$true, ParameterSetName="specifyKey")] [string]$secretKey,
        [parameter(ParameterSetName="credentialsFile")] [string]$credentialsFile = "$env:USERPROFILE\.aws\credentials"
    )
    switch($PsCmdlet.ParameterSetName)
    {
        "specifyKey" {
            $env:awsAccessKeyId = $accessKey
            $env:awsSecretKey = $secretKey
            break
        }
        "credentialsFile" {
            $env:awsAccessKeyId = Read-ValueForKeyFromFile -from $credentialsFile -field AWSAccessKeyId
            $env:awsSecretKey = Read-ValueForKeyFromFile -from $credentialsFile -field AWSSecretKey
            break
        }
    }
    $config = New-Object Amazon.S3.AmazonS3Config
    $config.WithServiceURL("https://s3.eu-west-1.amazonaws.com")
    $client = New-Object Amazon.S3.AmazonS3Client($env:awsAccessKeyId, $env:awsSecretKey, $config)
    return $client
}

我想提取参数 2-4 包括到CommonParameters,然后将 switch 块提取到一些常用功能。

4

1 回答 1

0

我遇到的大多数模块都使用 Connect-SomeService 函数,然后处理模块状态中的连接/凭据。也许它的某些部分暴露在调用者会话中(数组变量跟踪连接)。

像 VMware PowerCLI...

Connect-VIServer

获取虚拟机

这样,您只需在 Connect-S3Service 函数中请求凭据。该命令将连接保存在所有其他函数默认使用的变量中。但是,这样做意味着您仍然希望在所有其他功能中拥有一个 $S3Service 通用参数(以防您只想将作业发送到特定连接),但至少要少两个参数。

于 2012-02-27T22:35:34.800 回答