【问题标题】:How to define further commonparameters for powershell functions defined within a bespoke module?如何为定制模块中定义的 powershell 函数定义更多通用参数?
【发布时间】:2012-02-27 18:00:40
【问题描述】:

我正在编写一个 powershell 模块来与 AWS 交互。大多数函数都需要接受作为要使用的凭据的参数 - awsAccessKeyIdawsSecretKeycredentialsFile

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

对于模块导出的函数集,有没有办法声明这些是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块提取到一些常用功能。

【问题讨论】:

    标签: powershell refactoring powershell-2.0 powershell-module


    【解决方案1】:

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

    像 VMware PowerCLI...

    Connect-VIServer

    Get-VM

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2010-11-18
      • 2014-07-21
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多