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

从C#调用PowerShell安装使用Az模块报错问题排查

问题描述

在.NET 6的C#程序中调用PowerShell脚本安装并使用Az库时,出现以下错误:

执行测试失败,原因:
New-AzResourceGroup:
行号 |
8 | New-AzResourceGroup -Name 'TestRg123' -Location 'eastus2euap'
| ~~~~~~~~~~~~~~~~~~~
| 术语“New-AzResourceGroup”未被识别为 cmdlet、函数、脚本文件或可执行程序的名称。请检查名称的拼写,如果包含路径,请验证路径是否正确,然后重试。

推测问题出在Az模块未安装成功,或是C#代码执行过快,导致导入和安装命令被忽略。

注:实际脚本功能远不止创建资源组,因此无法改用Azure C# SDK实现。


相关代码

App.cs

using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

var initialState = InitialSessionState.CreateDefault2();
initialState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

using var ps = PowerShell.Create(initialState);
var results = ps.AddScript(@"
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

# Import Azure module
Import-Module 'Az'
Import-Module 'Az.Accounts'
Import-Module 'Az.RecoveryServices'

try {
    New-AzResourceGroup -Name 'TestRg123' -Location 'eastus2euap'
}
catch
{
    $string_err = $_ | Out-String
    Write-Output ""Failed to run test $testname because $string_err""
}
").Invoke();

foreach (var outputItem in results)
{
    Debug.WriteLine(outputItem);
}

ConsoleApp.csproj

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.6" />
      <PackageReference Include="PowerShellStandard.Library" Version="5.1.1" />
      <PackageReference Include="System.Management.Automation" Version="7.2.6" />
    </ItemGroup>

</Project>

更新:错误缓冲区内容

查看ps.ErrorBuffer后发现,安装模块阶段存在错误:

Install-Module: 无法安装模块 'Az',因为未信任存储库 'PSGallery'。请使用 Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted 命令将存储库设置为受信任,然后重试。


解决方案
  1. 信任PSGallery存储库
    在安装Az模块前,先执行存储库信任命令,确保模块能正常下载:

    Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
    
  2. 优化模块安装与加载逻辑
    安装时添加-AllowClobber避免冲突,安装后刷新模块路径并强制导入,确保模块被正确加载:

    Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
    Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force -AllowClobber
    # 刷新系统模块路径,确保新安装的模块能被检测到
    $env:PSModulePath = [System.Environment]::GetEnvironmentVariable("PSModulePath","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PSModulePath","User")
    # 强制导入模块
    Import-Module Az -Force
    Import-Module Az.Accounts -Force
    Import-Module Az.RecoveryServices -Force
    
  3. 添加安装阶段错误捕获
    在脚本中增加安装模块的错误处理,提前排查安装失败问题:

    try {
        Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force -AllowClobber -ErrorAction Stop
        Write-Output "Az模块安装成功"
    } catch {
        $install_err = $_ | Out-String
        Write-Output "Az模块安装失败:$install_err"
        exit 1
    }
    
  4. 确认运行权限
    确保程序运行时具备足够权限(如管理员权限),避免因权限不足导致模块安装失败。


内容的提问来源于stack exchange,提问作者Node.JS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:41:04