You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从.NET/C#或PowerShell以编程方式调用执行Azure CLI命令?

嘿,这事儿我熟!不管你是用PowerShell还是.NET/C#,都能轻松实现编程式执行Azure CLI命令,下面给你一步步拆解可行的方案:

在PowerShell中编程执行Azure CLI命令

PowerShell和Azure CLI天生适配,直接调用az命令就行,还能轻松捕获输出、处理执行状态:

  • 直接执行命令并解析输出
    比如获取所有资源组,把JSON输出转成PowerShell对象方便后续处理:

    # 执行Azure CLI命令并将JSON输出转为PowerShell对象
    $resourceGroups = az group list --output json | ConvertFrom-Json
    
    # 遍历输出结果
    foreach ($rg in $resourceGroups) {
        Write-Host "资源组:$($rg.Name),位置:$($rg.Location)"
    }
    
  • 动态传递参数
    如果需要根据变量构建命令,直接拼接参数就行,还能检查执行是否成功:

    $targetRg = "my-test-rg"
    $targetVm = "my-test-vm"
    
    # 启动指定VM
    $executionOutput = az vm start --name $targetVm --resource-group $targetRg
    
    # 检查命令退出码判断执行结果(0表示成功)
    if ($LASTEXITCODE -eq 0) {
        Write-Host "VM启动成功!"
    } else {
        Write-Error "启动失败,错误信息:$executionOutput"
    }
    

注意:如果机器上的Azure CLI不在默认PATH里,可以指定az.cmd的完整路径,比如& "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" group list

在.NET/C#中编程执行Azure CLI命令

如果用C#,可以通过调用系统进程来执行az命令,或者用更原生的Azure .NET SDK(推荐优先用SDK,类型更安全):

方案1:直接调用进程执行Azure CLI命令

用Process类启动az.exe,捕获输出和错误信息:

using System;
using System.Diagnostics;
using System.Text;

namespace AzureCliExecutor
{
    class Program
    {
        static void Main(string[] args)
        {
            // 要执行的Azure CLI命令参数
            string cliArgs = "group list --output json";
            var (output, error, exitCode) = RunAzCommand(cliArgs);

            Console.WriteLine("命令输出:");
            Console.WriteLine(output);

            if (exitCode != 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"执行失败,错误:{error}");
                Console.ResetColor();
            }
        }

        static (string Output, string Error, int ExitCode) RunAzCommand(string commandArgs)
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = "az",
                Arguments = commandArgs,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8
            };

            using var process = Process.Start(startInfo);
            process.WaitForExit();

            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            return (output, error, process.ExitCode);
        }
    }
}

注意:

  • 确保az.exe在系统PATH中,或者指定完整路径(比如FileName = @"C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\az.exe")
  • 处理编码问题,避免中文输出乱码
  • 如果需要异步执行,可以使用process.WaitForExitAsync()替代同步等待

方案2:用Azure .NET SDK替代CLI命令

如果只是想实现Azure CLI的功能,更推荐用官方的Azure .NET SDK,它是原生API,类型安全,不需要解析字符串输出:

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using System;
using System.Threading.Tasks;

namespace AzureSdkExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 使用默认凭据认证(支持环境变量、Azure CLI登录、VS认证等)
            var armClient = new ArmClient(new DefaultAzureCredential());

            // 获取默认订阅
            var subscription = await armClient.GetDefaultSubscriptionAsync();

            // 获取所有资源组
            await foreach (var resourceGroup in subscription.GetResourceGroups().GetAllAsync())
            {
                Console.WriteLine($"资源组:{resourceGroup.Data.Name},位置:{resourceGroup.Data.Location}");
            }
        }
    }
}

使用前需要安装对应的NuGet包,比如Azure.ResourceManager.Resources和Azure.Identity。

内容的提问来源于stack exchange,提问作者AKR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:43:53