Отсутствует модуль AzureRmProfileProvider

В настоящее время я нахожусь в 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

person Brandon Michael Hunter    schedule 05.04.2018    source источник
comment
Не удалось найти тип [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]. В строке: 74 символа: 19 + ... RmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstracti ... + ~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: InvalidOperation: (Microsoft.Azure ... ProfileProvider: TypeName) [], RuntimeException + FullyQualifiedErrorId: TypeNotFound   -  person Brandon Michael Hunter    schedule 06.04.2018
comment
Выше приведена ошибка, которую я получаю   -  person Brandon Michael Hunter    schedule 06.04.2018


Ответы (2)


Вероятно, проблема в том, что вы используете устаревшие модули Azure или, по крайней мере, они не соответствуют тому, который вы установили на свой компьютер. Попробуйте обновить модули Azure в своей учетной записи службы автоматизации. Также убедитесь, что модули, которые вы используете, тоже включены.

введите описание изображения здесь

person Bruno Faria    schedule 06.04.2018

В моем случае ничего не связанного с устаревшими модулями Azure.

Проблема возникает из-за того, что ps не смог найти тип во время синтаксического анализа, но он доступен во время выполнения. Так что просто обмануть синтаксический анализатор, сохранив командлет внутри литерала, выполняемого с помощью invoke-command, он работает:

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

С Уважением.

person Josto    schedule 01.02.2021