Joh*_*aul 16 authentication powershell azure
我正在编写Azure PowerShell脚本并登录到Azure I调用Add-AzureAccount,它将弹出浏览器登录窗口.
我想知道什么是检查身份验证凭据是否已过期的最佳方法,因此我是否应该Add-AzureAccount再次呼叫?
我现在所做的是,我只是打电话Get-AzureVM,看看是否$?等于$False.对我来说听起来有些讨厌,但似乎有效.如果订阅没有部署任何虚拟机,它仍然可以工作吗?
小智 30
Azure RM,但这将检查是否有活动帐户,否则抛出提示.
if ([string]::IsNullOrEmpty($(Get-AzureRmContext).Account)) {Login-AzureRmAccount}
Run Code Online (Sandbox Code Playgroud)
干杯
Avi*_*zra 19
您需要运行Get-AzureRmContext并检查是否填充了Account属性.在最新版本的AzureRM中,Get-AzureRmContext不会引发错误(由需要活动会话的cmdlet引发错误).然而,显然在其他一些版本中它确实如此.
这对我有用:
function Login
{
$needLogin = $true
Try
{
$content = Get-AzureRmContext
if ($content)
{
$needLogin = ([string]::IsNullOrEmpty($content.Account))
}
}
Catch
{
if ($_ -like "*Login-AzureRmAccount to login*")
{
$needLogin = $true
}
else
{
throw
}
}
if ($needLogin)
{
Login-AzureRmAccount
}
}
Run Code Online (Sandbox Code Playgroud)
我会让它比彼得提出的要简单一些.只需在脚本开头的某处插入这些行:
Try {
Get-AzureRmContext
} Catch {
if ($_ -like "*Login-AzureRmAccount to login*") {
Login-AzureRmAccount
}
}
Run Code Online (Sandbox Code Playgroud)
干杯,
小智 5
为此,我创建了一个在脚本中使用的模块。它使用Get-AzAccessTokencmdlet。
function Get-AzLogin {
<#
.SYNOPSIS
Checks AZ login status and account
.DESCRIPTION
Use this module to check Azure PowerShell login status and make sure that user is logged in.
It also accepts either subscription name or ID to be set right after checking login.
.EXAMPLE
Get-AzLogin
.EXAMPLE
Get-AzLogin [[-Subscription] <string>]
#>
param (
[string] $Subscription
)
Write-Host "[Get-AzLogin] Checking Azure PowerShell Login... " -NoNewline
# Check if logged in to Azure PowerShell
$AccessToken = Get-AzAccessToken -ErrorAction SilentlyContinue
if (!$AccessToken) {
Write-Host "Login needed"
try {
Login-AzAccount -ErrorAction stop > Out-Null
}
catch
{
throw "Could not login to Azure"
}
} else {
Write-Host "Already logged in"
}
# Try setting subscription if provided
if ($Subscription) {
Write-Host "[Get-AzLogin] Found subscription as argument. Will run Set-AzContext... " -NoNewline
try {
Set-AzContext -SubscriptionId $Subscription -ErrorAction stop | Out-Null
Write-Host "set to $((get-azcontext).Subscription.name)"
}
catch
{
throw "Could not set Subscription $Subscription"
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11628 次 |
| 最近记录: |