diff --git a/src/Common/AzurePSCmdlet.cs b/src/Common/AzurePSCmdlet.cs index 3b1de0c4f3..26743c995b 100644 --- a/src/Common/AzurePSCmdlet.cs +++ b/src/Common/AzurePSCmdlet.cs @@ -870,32 +870,47 @@ public virtual bool IsTerminatingError(Exception ex) protected string LoadAzVersion() { - Version latestAz = new Version("0.0.0"); + Version defautVersion = new Version("0.0.0"); + if (this.Host == null) + { + WriteDebug("Cannot fetch Az version due to no host in current environment"); + return defautVersion.ToString(); + } + + Version latestAz = defautVersion; string latestSuffix = ""; using (var powershell = System.Management.Automation.PowerShell.Create()) { - powershell.Runspace = RunspaceFactory.CreateRunspace(this.Host); - powershell.AddCommand("Get-Module"); - powershell.AddParameter("Name", "Az"); - powershell.AddParameter("ListAvailable", true); - powershell.Runspace.Open(); - Collection outputs = powershell.Invoke(); - foreach (PSObject obj in outputs) + try { - string psVersion = obj.Properties["Version"].Value.ToString(); - int pos = psVersion.IndexOf('-'); - string currentSuffix = (pos == -1 || pos == psVersion.Length - 1) ? "" : psVersion.Substring(pos + 1); - Version currentAz = (pos == -1) ? new Version(psVersion) : new Version(psVersion.Substring(0, pos)); - if (currentAz > latestAz) - { - latestAz = currentAz; - latestSuffix = currentSuffix; - } - else if (currentAz == latestAz) + powershell.Runspace = RunspaceFactory.CreateRunspace(this.Host); + powershell.AddCommand("Get-Module"); + powershell.AddParameter("Name", "Az"); + powershell.AddParameter("ListAvailable", true); + powershell.Runspace.Open(); + Collection outputs = powershell.Invoke(); + foreach (PSObject obj in outputs) { - latestSuffix = String.Compare(latestSuffix, currentSuffix) > 0 ? latestSuffix : currentSuffix; + string psVersion = obj.Properties["Version"].Value.ToString(); + int pos = psVersion.IndexOf('-'); + string currentSuffix = (pos == -1 || pos == psVersion.Length - 1) ? "" : psVersion.Substring(pos + 1); + Version currentAz = (pos == -1) ? new Version(psVersion) : new Version(psVersion.Substring(0, pos)); + if (currentAz > latestAz) + { + latestAz = currentAz; + latestSuffix = currentSuffix; + } + else if (currentAz == latestAz) + { + latestSuffix = String.Compare(latestSuffix, currentSuffix) > 0 ? latestSuffix : currentSuffix; + } } } + catch (Exception e) + { + WriteDebug(string.Format("Cannot fetch Az version due to exception: {0}", e.Message)); + return defautVersion.ToString(); + } } string ret = latestAz.ToString(); if (!String.IsNullOrEmpty(latestSuffix))