缺少AzureRmProfileProvider模块

时间:2018-04-05 21:20:59

标签: powershell azure azure-resource-manager azure-runbook

我目前在Azure中尝试使用PowerShell脚本执行运行手册,而我的脚本会发出错误,因为它无法找到此类: Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider

您能帮忙了解如何将此类添加到我的脚本中吗?

以下是我的剧本:

[CmdletBinding()]
[OutputType([string])]
Param
(
  # VM Name
  [Parameter(Mandatory = $true,
      ValueFromPipelineByPropertyName = $true,
  Position = 0)]
  $VMName
)

$VerbosePreference = 'Continue' #remove when publishing runbook

#region Runbook variables
Write-Verbose -Message 'Retrieving hardcoded Runbook Variables'
$Resourcegroupname = 'scriptextensiondemo-rg'
$ExtensionName = 'WindowsUpdate'
$APIVersion = '2017-03-30'
$ScriptExtensionUrl = 'https://[enteryourvaluehere].blob.core.windows.net/script/Install-WindowsUpdate.ps1'
#endregion

#region Connection to Azure
Write-Verbose -Message 'Connecting to Azure'
$connectionName = 'AzureRunAsConnection'

try
{
  # Get the connection "AzureRunAsConnection "
  $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName         

  'Logging in to Azure...'
  Add-AzureRmAccount `
  -ServicePrincipal `
  -TenantId $servicePrincipalConnection.TenantId `
  -ApplicationId $servicePrincipalConnection.ApplicationId `
  -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch 
{
  if (!$servicePrincipalConnection)
  {
    $ErrorMessage = "Connection $connectionName not found."
    throw $ErrorMessage
  }
  else
  {
    Write-Error -Message $_.Exception.Message
    throw $_.Exception
  }
}
#endregion

#region Get AccessToken
Write-Verbose 'Get Access Token'
$currentAzureContext = Get-AzureRmContext
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azureRmProfile)
$token = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId)
#endregion 

#region Get extension info
Write-Verbose -Message 'Get extension info'
$Uri = 'https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/extensions/{3}?api-version={4}' -f $($currentAzureContext.Subscription), $Resourcegroupname, $VMName, $ExtensionName, $APIVersion
$params = @{
  ContentType = 'application/x-www-form-urlencoded'
  Headers     = @{
    'authorization' = "Bearer $($token.AccessToken)"
  }
  Method      = 'Get'
  URI         = $Uri
}
$ExtensionInfo = Invoke-RestMethod @params -ErrorAction SilentlyContinue
if (!($ExtensionInfo)) 
{
  Write-Verbose 'No Custom Script Extension Configured. Please do an initial script configuration first'
  #region configure custom script extension
  $Uri = 'https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/extensions/{3}?api-version={4}' -f $($currentAzureContext.Subscription), $Resourcegroupname, $VMName, $ExtensionName, '2017-03-30'

  $body = @"
{
  "location": "westeurope",
  "properties": {
    "publisher":  "Microsoft.Compute",
    "type": "CustomScriptExtension",
    "typeHandlerVersion": "1.4",
    "autoUpgradeMinorVersion": true,
    "forceUpdateTag": "InitialConfig",
    "settings": {
       "fileUris" : ["$ScriptExtensionUrl"],
       "commandToExecute": "powershell -ExecutionPolicy Unrestricted -file Install-WindowsUpdate.ps1"
    }
  }
}
"@

  $params = @{
    ContentType = 'application/json'
    Headers     = @{
      'authorization' = "Bearer $($token.AccessToken)"
    }
    Method      = 'PUT'
    URI         = $Uri
    Body        = $body
  }

  $InitialConfig = Invoke-RestMethod @params
  $InitialConfig
  exit
  #endregion
}
#endregion

#region Get Extension message info
Write-Verbose 'Get Extension message info'
$Uri = 'https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/extensions/{3}?$expand=instanceView&api-version={4}' -f $($currentAzureContext.Subscription), $Resourcegroupname, $VMName, $ExtensionName, $APIVersion
$params = @{
  ContentType = 'application/x-www-form-urlencoded'
  Headers     = @{
    'authorization' = "Bearer $($token.AccessToken)"
  }
  Method      = 'Get'
  URI         = $Uri
}
$StatusInfo = Invoke-RestMethod @params
#$StatusInfo
[regex]::Replace($($StatusInfo.properties.instanceView.SubStatuses[0].Message), '\\n', "`n")
#endregion

#region Update Script Extension
try
{
  Write-Verbose 'Update Script Extension'
  $Uri = 'https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}/extensions/{3}?api-version={4}' -f $($currentAzureContext.Subscription), $Resourcegroupname, $VMName, $ExtensionName, '2017-03-30'

  $body = @"
{
  "location": "westeurope",
  "properties": {
    "publisher":  "Microsoft.Compute",
    "type": "CustomScriptExtension",
    "typeHandlerVersion": "1.4",
    "autoUpgradeMinorVersion": true,
    "forceUpdateTag": "$(New-Guid)",
    "settings": {
       "fileUris" : ["$ScriptExtensionUrl"],
       "commandToExecute": "powershell -ExecutionPolicy Unrestricted -file Install-WindowsUpdate.ps1"
    }
  }
}
"@

  $params = @{
    ContentType = 'application/json'
    Headers     = @{
      'authorization' = "Bearer $($token.AccessToken)"
    }
    Method      = 'PUT'
    URI         = $Uri
    Body        = $body
  }

  $Updating = Invoke-RestMethod @params
  $Updating
}
catch
{
  Write-Error -Message $_.Exception.Message
  throw $_.Exception
}
#endregion

2 个答案:

答案 0 :(得分:1)

问题可能在于您运行过时的Azure模块,或者至少它们与您计算机中安装的Azure模块不匹配。尝试更新自动化帐户中的Azure模块。还要确保包含您正在使用的模块。

enter image description here

答案 1 :(得分:0)

就我而言,与过时的 Azure 模块无关。

问题来自于 ps 在解析期间无法找到类型但在执行期间可用的事实。因此,只需通过将命令行开关存储在使用 invoke-command 执行的文字中来“欺骗”解析器即可:

$profile = Invoke-Expression "[Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile"

问候。