使用az vm run-command invoke在Azure VM安装软件失败求助
解决Azure VM中
choco命令未被识别的问题 问题原因
Chocolatey安装完成后,其路径会被添加到系统环境变量PATH中,但PowerShell会话不会自动加载新的环境变量配置。当你通过az vm run-command invoke执行脚本时,新启动的PowerShell会话无法读取到Chocolatey的路径,因此出现choco命令未识别的错误。另外,若之前通过Custom Script Extension安装Chocolatey未成功,也会导致该问题。
解决方法
方法1:直接使用Chocolatey的完整路径执行命令
跳过环境变量依赖,直接调用Chocolatey的可执行文件路径:
az vm run-command invoke -g "xxx" -n "xx" --command-id RunpowerShellScript --scripts "& '$env:ProgramData\chocolatey\bin\choco.exe' install notepadplusplus -y"
- 加上
-y参数可以自动确认安装,避免脚本因等待用户输入而卡住。
方法2:在脚本中刷新环境变量后执行命令
先刷新当前PowerShell会话的环境变量,让系统识别到Chocolatey的路径:
az vm run-command invoke -g "xxx" -n "xx" --command-id RunpowerShellScript --scripts "$env:Path = [System.Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path','User'); choco install notepadplusplus -y"
- 此方法适用于已确认Chocolatey安装成功,但环境变量未生效的场景。
方法3:在同一个脚本中安装并调用Chocolatey
如果不确定之前的Chocolatey安装是否成功,可以在同一个脚本中完成安装+环境变量刷新+软件安装的全流程:
az vm run-command invoke -g "xxx" -n "xx" --command-id RunpowerShellScript --scripts "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')); $env:Path = [System.Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path','User'); choco install notepadplusplus -y"
验证安装结果
执行完命令后,可以通过以下命令验证Notepad++是否安装成功:
az vm run-command invoke -g "xxx" -n "xx" --command-id RunpowerShellScript --scripts "Get-ChildItem -Path 'C:\Program Files\Notepad++\notepad++.exe'"
内容的提问来源于stack exchange,提问作者learner
相关产品推荐
相关产品推荐

