在 C# 中为 Azure 自动化帐户构建模块

Building Module for Azure Automation Account in C#

我正在尝试创建一个类似于以下 Powershell 命令的 C# CmdLet:-

$myCred = Get-AutomationPSCredential -Name $Automation_Credentials
$userName = $myCred.UserName
$password = $myCred.GetNetworkCredential().Password 

所以我可以做相当于

$prep = [System.Text.Encoding]::ASCII.GetBytes(${authpair})    
$base64 = [System.Convert]::ToBase64String(${prep})    
$basicAuthValue = "Basic $base64" 

然后

Invoke-RestMethod

我看到已经落在了相当于

的第一个障碍
Get-AutomationPSCredential -Name $Automation_Credentials

在 C# Cmdlet 中。

C# CmdLet 的框架如下所示:-

namespace MyNamespace
{
    using System.Management.Automation;

    [Cmdlet(VerbsCommunications.Connect, "Ka")]
    public class ConnectKa
        : Cmdlet
    {
        /// <summary>
        ///     The base URL  e.g. http://localhost:8081
        /// </summary>
        [Parameter (Position = 0, 
            HelpMessage="The base URL e.g. http://localhost:8081",
            Mandatory= true)]
        public string BaseUrl { get; set; } = null;

        /// <summary>
        ///     The name of the Cluster to authenticate against
        ///     (not necessarily the cluster we are running the commands against).
        /// </summary>
        [Parameter (Position = 1, 
            HelpMessage="The name of the Cluster to authenticate against (not necessarily the cluster " +
                        "we are running the commands against).",
            Mandatory= true)]
        public string Cluster_Name { get; set; } = null;

        [Parameter (Position = 2, 
            HelpMessage="The name of the Azure AutomationAccount to log in with.",
            Mandatory= true)]
        public string Automation_Credentials { get; set; } = null;

        /// <summary>
        ///     Perform Cmdlet processing.
        /// </summary>
        protected override void ProcessRecord()
        {
            // Need to perform the equivalent of the following Powershell
            //  $myCred = Get-AutomationPSCredential -Name $Automation_Credentials
            //  $userName = $myCred.UserName
            //  $password = $myCred.GetNetworkCredential().Password  
            //  $authpair = "${userName}:${password}" 
        }
    }
}

Azure 自动化中的 Get-AutomationPSCredential 命令很特殊:它的实现使用平台内部机制来正确检索机密。您不想复制这段代码:它相对复杂,您的副本可能随时停止工作,因为它依赖于内部组件之间的接口,可以随时更改,恕不另行通知。

如果您想在 Get-AutomationPSCredential 的基础上做一些事情,更好的办法是调用原始的 Get-AutomationPSCredential 命令,捕获输出,然后执行额外的处理。