in src/Cli/func/Actions/AzureActions/BaseAzureAction.cs [207:275]
private async Task<(bool Succeeded, string Token)> TryGetAzPowerShellToken()
{
// PowerShell Core can only use Az so we can check that it exists and that the Az module exists
if (CommandChecker.CommandExists(PowerShellCoreExecutable) &&
await CommandChecker.PowerShellModuleExistsAsync(PowerShellCoreExecutable, AzProfileModuleName))
{
var az = new Executable(PowerShellCoreExecutable, $"-NonInteractive -o Text -NoProfile -c {GetPowerShellAccessTokenScript(AzProfileModuleName)}");
var stdout = new StringBuilder();
var stderr = new StringBuilder();
var exitCode = await az.RunAsync(o => stdout.AppendLine(o), e => stderr.AppendLine(e));
if (exitCode == 0)
{
return (true, stdout.ToString().Trim(' ', '\n', '\r', '"'));
}
else
{
if (StaticSettings.IsDebug)
{
ColoredConsole.WriteLine(VerboseColor($"Unable to fetch access token from Az.Profile in PowerShell Core. Error: {stderr.ToString().Trim(' ', '\n', '\r')}"));
}
}
}
// Windows PowerShell can use Az or AzureRM so first we check if powershell.exe is available
if (CommandChecker.CommandExists(WindowsPowerShellExecutable))
{
string moduleToUse;
// depending on if Az.Profile or AzureRM.Profile is available, we need to change the prefix
if (await CommandChecker.PowerShellModuleExistsAsync(WindowsPowerShellExecutable, AzProfileModuleName))
{
moduleToUse = AzProfileModuleName;
}
else if (await CommandChecker.PowerShellModuleExistsAsync(WindowsPowerShellExecutable, AzureRmProfileModuleName))
{
moduleToUse = AzureRmProfileModuleName;
}
else
{
// User doesn't have either Az.Profile or AzureRM.Profile
if (StaticSettings.IsDebug)
{
ColoredConsole.WriteLine(VerboseColor("Unable to find Az.Profile or AzureRM.Profile."));
}
return (false, null);
}
var az = new Executable("powershell", $"-NonInteractive -o Text -NoProfile -c {GetPowerShellAccessTokenScript(moduleToUse)}");
var stdout = new StringBuilder();
var stderr = new StringBuilder();
var exitCode = await az.RunAsync(o => stdout.AppendLine(o), e => stderr.AppendLine(e));
if (exitCode == 0)
{
return (true, stdout.ToString().Trim(' ', '\n', '\r', '"'));
}
else
{
if (StaticSettings.IsDebug)
{
ColoredConsole.WriteLine(VerboseColor($"Unable to fetch access token from '{moduleToUse}'. Error: {stderr.ToString().Trim(' ', '\n', '\r')}"));
}
}
}
return (false, null);
}