简体   繁体   中英

What's the proper way to create a case-loop/switch-statement-type PowerShell function?

Because of the possibility that I'm really stuck on an XY problem here, what I'm actually doing is writing a rather large script to handle user administration for on-prem and cloud-based users on a Windows platform. This means a handful of on-prem services, authenticated using Active Directory credentials, and a handful of cloud-based services, using Azure Active Directory credentials. Ideally, there would be one set of credentials that could perform all the actions, but I can't rely on that, which leaves me looking for a way to get a number of credentials (I'm up to about 8) that will then be sent on to the appropriate Connect-[Service] function I've written.

I think the proper way to write this function is with a switch statement, along the lines of:

Function Get-Credentials {
    Param (
        [Parameter(Mandatory=$true)][string]$Service
    )

    $global:Service1Credentials = $null;
    $global:Service2Credentials = $null;
    ...

    switch ($Service)
    {
        Service1 { $global:Service1Credentials = Get-Credential  -Message "Credentials for [Service1]"}
        Service2 { $global:Service2Credentials = Get-Credential  -Message "Credentials for [Service2]"}
        ...
    }
}

Ignoring the use of global parameters (which I'm doing for better debugability while I write the script), is this the proper approach to the problem of getting credentials for a script to use against several to a dozen different services, or is there a better approach I should be using?

Here is an alternative that will be a little less cumbersome as the switch options grow:

function Get-SvcCred($ServiceName)
{
    return (Get-Credential  -Message "Credentials for $ServiceName")
}

$services = "Service1", "Service2", "Service3"

$creds = @{}

$services | 
    ForEach-Object {
        $creds[$_] = Get-SvcCred $_
    }

Now, all you have to do is update the $services array as new ones are added and this will correctly ask for each one in turn. The added benefit is that you can easily access any set of credentials later in the code by doing something like this:

$creds["Service1"]

Obviously, if you don't want (or need) the user to give all the credentials at once, you can simply make each call as and when required:

$creds["Service3"] = Get-SvcCred "Service3"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM