Azure自动化Runbook执行Invoke-AzVMRunCommand更新VM注册表失败求助
Azure自动化Runbook更新VM注册表失败问题排查与修复
下面是你的代码中存在的核心问题以及修正方案:
问题点分析
Invoke-AzVMRunCommand参数误用
你用-ScriptPath传递脚本块$ScriptBlock,但这个参数是用来指定本地脚本文件路径的(比如C:\xxx\script.ps1),直接传脚本块应该用-ScriptString参数,把脚本内容转为字符串传递。注册表项名称错误
你把RegistryName设为$RegistrationToken(整个令牌对象),但RDInfraAgent要求的注册表项名称是固定字符串RegistrationToken,这会导致创建错误的注册表项,根本无法被识别。Run Command参数格式错误
Invoke-AzVMRunCommand的-Parameter需要的是包含Name和Value的哈希表数组,不是单个哈希表,当前格式会导致参数无法正确传递到VM内部的脚本。潜在前置条件问题
要确保自动化账户有Microsoft.Compute/virtualMachines/runCommand/action权限,且目标VM处于运行状态,否则Run Command根本无法执行。
修正后的完整代码
try { "Logging in to Azure..." Connect-AzAccount -Identity } catch { Write-Error -Message $_.Exception throw $_.Exception } # Set the subscription (if not already set) Set-AzContext -SubscriptionId "xxxxxxxxxxxxxxxx" $ResourceGroupName = "xxxxx1" $HostPoolName = "wpxxxxxxxxx" # Check if the host pool exists $Hostpool = Get-AzWvdHostPool -Name $HostPoolName -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue if (!$Hostpool) { Write-Host '', "Hostpool '$($HostPoolName)' doesn't exist. It will be created by TF" } else { try { # Create token $RegistrationToken = New-AzWvdRegistrationInfo -ResourceGroupName $ResourceGroupName ` -HostPoolName $HostPoolName ` -ExpirationTime (Get-Date).ToUniversalTime().AddHours(2).ToString('yyyy-MM-ddTHH:mm:ss.fffffffZ') Write-Host '', "Token created" Write-Output $RegistrationToken } catch { throw $_.Exception } } $VMName = "001" # 将脚本内容转为字符串,适配Run Command的参数要求 $ScriptString = @" param ( [string]`$RegistryPath, [string]`$RegistryName, [string]`$NewRegistryValueData ) # 检查注册表路径是否存在,不存在则创建 if (-not (Test-Path `$RegistryPath)) { try { New-Item -Path `$RegistryPath -Force -ErrorAction Stop Write-Output "Registry key '`$RegistryPath' created successfully." } catch { Write-Error "Failed to create registry key '`$RegistryPath': `$_" } } # 更新注册表值 try { Set-ItemProperty -Path `$RegistryPath -Name `$RegistryName -Value `$NewRegistryValueData -ErrorAction Stop Write-Output '', "Registry value updated" } catch { Write-Error -Message "Failed to update registry value: `$_" } "@ # 按Run Command要求的格式准备参数 $Parameters = @( @{ Name = "RegistryPath"; Value = "HKLM:\SOFTWARE\Microsoft\RDInfraAgent" }, @{ Name = "RegistryName"; Value = "RegistrationToken" }, # 固定的注册表项名称 @{ Name = "NewRegistryValueData"; Value = $RegistrationToken.Token } ) # 执行VM Run Command并捕获结果 try { $runResult = Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName ` -VMName $VMName ` -CommandId 'RunPowerShellScript' ` -ScriptString $ScriptString ` -Parameter $Parameters # 输出执行结果,方便排查问题 Write-Host "Run Command执行输出:" Write-Output $runResult.Value.Message } catch { Write-Error "执行Run Command失败: $_" throw $_ }
修正说明
- 改用
-ScriptString传递脚本内容,解决参数误用问题 - 固定注册表项名称为
RegistrationToken,匹配RDInfraAgent的官方要求 - 调整参数格式为数组结构,确保参数能正确传递到VM内部
- 添加了执行结果的输出,方便后续排查执行过程中的问题
内容的提问来源于stack exchange,提问作者Madhu
相关产品推荐
相关产品推荐

