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

Azure DSC配置执行报错:Get-AutomationPSCredential cmdlet未被识别

解决Azure DSC中Get-AutomationPSCredential未识别的错误

这个报错的核心原因很明确:Get-AutomationPSCredential和Get-AutomationVariable是Azure Automation Runbook专属的cmdlet——它们只能在Automation账户的沙箱环境中运行,依赖Automation内部的资源访问机制;而你的DSC配置是推送到目标VM节点本地执行的,节点环境里根本没有这些cmdlet,自然会报错。虽然Runbook里能正常执行,但两者的运行环境完全不同。

下面是具体的解决方案:

1. 调整配置:通过参数传递资源值

不要在DSC的SetScript里直接调用Automation专属cmdlet,而是把凭证和订阅ID作为配置参数传入。编译配置时从Automation账户获取这些值,再打包进MOF文件,节点执行时就能直接使用了。

修改后的配置代码:

Configuration VMAzureDSCTasks {
    param (
        [Parameter()] [System.String] $NodeName = "rajeshserver",
        [Parameter()] [System.String] $ResourceGroupName = "rajeshresourcegroup",
        [Parameter()] [System.Management.Automation.PSCredential] $VmCredential,
        [Parameter()] [System.String] $SubscriptionId,
        [Parameter()] [System.String] $VMSize = "Standard_D2s_v3"
    )
    Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
    Node $NodeName {
        # 先确保节点安装Azure PowerShell模块(建议用Az模块,AzureRM已弃用)
        PackageManagement InstallAzModule {
            Name = "Az"
            ProviderName = "PowerShellGet"
            Ensure = "Present"
            Source = "PSGallery"
        }

        Script resizevm {
            DependsOn = "[PackageManagement]InstallAzModule"
            SetScript = {
                # 直接使用传入的参数
                $null = Connect-AzAccount -Credential $using:VmCredential -ErrorAction Stop
                $null = Set-AzContext -SubscriptionId $using:SubscriptionId -ErrorAction Stop
                try {
                    $vm = Get-AzVm -ResourceGroupName $using:ResourceGroupName -VMName $using:NodeName -ErrorAction Stop
                } catch {
                    throw "Virtual Machine not found!!!!!!"
                    exit
                }
                # 输出当前VM规格
                $currentVMSize = $vm.HardwareProfile.vmSize
                Write-Verbose -Message "`nFound the specified Virtual Machine: $using:NodeName"
                Write-Verbose -Message "Current size: $currentVMSize"
            }
            TestScript = { return $false }
            GetScript = { }
        }
    }
}

2. 编译配置时传入Automation资源值

在Automation账户中编译这个配置时,先获取共享资源里的凭证和订阅ID,再作为参数传递给配置:

# 从Automation账户获取凭证和订阅ID
$cred = Get-AutomationPSCredential -Name "cred"
$subId = Get-AutomationVariable -Name "SubscriptionId"

# 编译配置并传递参数
VMAzureDSCTasks -NodeName "rajeshserver" -ResourceGroupName "rajeshresourcegroup" -VmCredential $cred -SubscriptionId $subId

编译生成的MOF文件会加密存储凭证信息,只要你正确配置了DSC的加密设置,安全性是有保障的。

额外说明

我把脚本里的AzureRM模块换成了Az模块——因为AzureRM已经正式弃用,后续Azure PowerShell的更新都会集中在Az模块上,建议你也同步升级,避免后续出现兼容性问题。

内容的提问来源于stack exchange,提问作者Rajesh Saradka Narayana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:33:16