安装 Azure CLI 并在同一脚本中运行 az login 命令,无需重新启动 power shell

use*_*005 2 powershell azure-cli azure-cli2

我正在开发一个自动化流程,使用 azure CLI (az 存储 blob 上传)将文件上传到 Azure blob,并且它按预期工作正常。

\n
    \n
  • Azure CLI 版本:2.17.1
  • \n
  • PowerShell版本:PS版本5.1.19041.610
  • \n
\n

如果用户计算机上没有安装 azure CLI,则当用户第一次运行 xe2\x80\x99s powershell 脚本时。我们正在安装(找到下面的代码)。但这里的要求是在从 PowerShell 安装 azure CLI 后,当我们执行“az login”时,我们会收到以下错误

\n
az : The term 'az' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is \ncorrect and try again.\nAt C:\\Users\\v-moush\\Desktop\\PowerShellerrorScript.ps1:13 char:1\n+ az login\n+ ~~\n    + CategoryInfo          : ObjectNotFound: (az:String) [], CommandNotFoundException\n    + FullyQualifiedErrorId : CommandNotFoundException\n
Run Code Online (Sandbox Code Playgroud)\n
Function Set-AzModule(){\n    $isAzureCliInstalled = Azure-CLI-Installed\n    if (!$isAzureCliInstalled) {\n        Write-Log \xe2\x80\x9cTrying to install Microsoft Azure CLI\xe2\x80\x9d\n        Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList \xe2\x80\x98/I AzureCLI.msi /quiet\xe2\x80\x99; rm .\\AzureCLI.msi\n        $isAzureCliInstalled = Azure-CLI-Installed;\n    \n        if (!$isAzureCliInstalled) {\n            Write-Log -message \xe2\x80\x9cUnable to install Microsoft Azure CLI\xe2\x80\x9d\n        }\n        else {\n            Write-Log -message \xe2\x80\x9cMicrosoft Azure CLI installed successfully\xe2\x80\x9d\n            az login\n            ## Here the command is failing power shell not able to find the az module\n        }\n    }\n}\n\nFunction Azure-CLI-Installed()\n{\n    # Check Microsoft Azure CLI is installed or not.\n    return (Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* |\n    Where { $_.DisplayName -eq \xe2\x80\x9cMicrosoft Azure CLI\xe2\x80\x9d }) -ne $null\n}\n
Run Code Online (Sandbox Code Playgroud)\n

查询:如何在同一脚本中安装 Azure CLI 后执行 az login 和其他 az 命令,而无需重新启动 Powershell 脚本?

\n

注意:我无法使用 azCopy 模块。

\n

use*_*005 5

使用以下命令修复了问题

 $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") 

Run Code Online (Sandbox Code Playgroud)

参考:在PowerShell中重新加载路径