Azure PowerShell - Object reference not set to an instance of an object - powershell

I'm trying to write a PowerShell script to automate EventHub creation using Azure PowerShell. I am following the documentation outlined here and have installed the Azure PowerShell module (v 1.0.3).
I have added the Microsoft ServiceBus library (v3.0) using the following
$scriptPath = Split-Path -parent $PSCommandPath
$dllPath = "$scriptPath\..\..\packages\WindowsAzure.ServiceBus.3.1.2\lib\net45-full\Microsoft.ServiceBus.dll"
Add-Type -Path $dllPath
But as soon as I try and use the Get-AzureSBNamespace command, e.g.
$CurrentNamespace = Get-AzureSBNamespace -Name $Namespace
I get the following error
Get-AzureSBNamespace : Object reference not set to an instance of an object.
the same is true of New-AzureSBNamespace. I have also tried logging into Azure within the same session using Login-AzureRmAccount, but get the same object null reference exception.
Is this a bug, or am i missing something not outlined in the documentation?

This is because it uses the Service Management API and not the Resource Manager API. For me I ran:
Add-AzureAccount
And then Get-AzureSBNamespace and other SB cmdlets started working just fine.

If you can use PS 5.0 give this a try: msdn

Related

Connect-AzureAD not working with Powershell core

I am trying to run a powershell command - ConnectAzureAD and getting the below error-
'Could not load file or assembly 'Microsoft.IdentityModel.Clients.ActiveDirectory, Version=3.19.7.16602, Culture=neutral,. Could not find or load a specific file.'
This was working earlier with Powershell 5 but not with powershell core.The versions that i am using are as:
Powershell - 7.0.1
Az.Accounts - 1.8.1 (i have tried updating this but no luck)
AzureAd - 2.0.2.104
Is there any workaroudn for this ? We tried Azure.Standard.Preview from 'Post test Gallery' but it failed the keyVault powershell commands. Any help on this?
Install-Module -Name AzureADPreview -RequiredVersion 2.0.2.89
Import-Module AzureADPreview -Version 2.0.2.89 -UseWindowsPowerShell
As Shiva said, this is a known limitation on .NET CORE that new version assembly cannot be loaded if old version is already loaded. PowerShell is considering module isolation but so far there is no good solution yet.
You can upgrade Microsoft.IdentityModel.Clients.ActiveDirectory to the latest version.
For more details, you could refer to this issue.
You could instead try to use the az rest invoking the graph api.
Until the time az-cli is in par with the AzureAD powershell module you can instead use the graph api
az login --tenant <tenantname.onmicrosoft.com>
$uri = "https://graph.microsoft.com/v1.0/applications"
$allApplications = az rest `
--method GET `
--uri $uri `
--headers 'Content-Type=application/json' | convertfrom-json
$allApplications.value |% {"{0}-{1}" -f $_.appid, $_.displayname}
I have put some samples using az rest here,
https://github.com/joepaulk/utilities/blob/master/manage-azuread-applicationregistrations.ps1
You may also refer to: https://damienbod.com/2020/06/22/using-azure-cli-to-create-azure-app-registrations/ from where i picked up inspiration
Other reference, how az rest use the accesstokens from az cli can be found here,
https://mikhail.io/2019/07/how-azure-cli-manages-access-tokens/

how to create folder and add file in azure web app using powershell

I am trying to do a simple task of creating a folder in an azure web app and add a file in it. Here is what I've achieved so far and need some help with the right commands
Add-AzureAccount
Select-AzureRmSubscription -SubscriptionName 'Demo'
$webApp = Get-AzureRmWebApp -Name 'test--app' -ResourceGroupName 'TEST-POC-AUTOMATION'
$webApp.<CANT FIGURE OUT WHICH COMMAND>
$root = 'D:\home\site\wwwroot\webapps\ROOT'
if (!(Test-Path $root))
{
md $root
}
I am trying to wonder if this is possible or i've to use KUDU API to achieve this. Appreciate any inputs.
You could use Kudu API to do this, check this link.
PUT /api/vfs/{path}/
Creates a directory at path. The path can be nested, e.g. `folder1/folder2`.
If you want to use Power Shell to call the API, you could check this example.

Powershell Azure : The term 'Get-AutomationConnection' is not recognized as the name of a cmdlet, function, script file, or operable program

I am trying to connect to an Azure Run As connection, as part of a Powershell script that does a backup of a database.
This script attempts to call Get-AutomationConnection
As seen in the screenshot, Get-Module does return that Azure / Azure.Storage and AzureRM shows.
What module should I import in addition for this to work?
If you want to connect to an Azure Run As connection from Windows PowerShell, you should use New-AzureRmAutomationConnection.
$ConnectionAssetName = "AzureRunAsConnection"
$ConnectionFieldValues = #{"ApplicationId" = $Application.ApplicationId; "TenantId" = $TenantID.TenantId; "CertificateThumbprint" = $Cert.Thumbprint; "SubscriptionId" = $SubscriptionId}
New-AzureRmAutomationConnection -ResourceGroupName $ResourceGroup -AutomationAccountName $AutomationAccountName -Name $ConnectionAssetName -ConnectionTypeName AzureServicePrincipal -ConnectionFieldValues $ConnectionFieldValues
You are able to use the script to create the connection asset because when you create your Automation account, it automatically includes several global modules by default along with the connection type AzurServicePrincipal to create the AzureRunAsConnection connection asset.
Get-AutomationConnection runs in Azure runbook internally.
Please refer to connection assets in Azure Automation.
If you want similar functionality to runbooks on-premise, you can install AzureAutomationAuthoringToolkit. It will give you very similar functionality. I have one script that logs in using the service principal, whether it is running on-premise or in an Azure runbook. It uses the resources provided by AAATK when running on-premise, that simulate a runbook.
I did try using the version of Get-AutomationConnection that comes with the "Microsoft Monitoring agent" (Hybrid worker), but I have since read that it is different to the one that comes with AzureAutomationAuthoringToolkit, detailed in the "Known Issues" in the GitHub readme. I couldn't get it to work, so I reverted to AAATK's version.

Azure Runbook load .Net assembly for application insight

I have requirement where I want to write some metrics to the application insight for monitoring a service at a regular interval.
I though that I would write this PowerShell script and schedule it accordingly.
Write-Output "Script Start"
$PSScriptRoot = Get-Location
$AI = "$PSScriptRoot\Microsoft.ApplicationInsights.dll"
[Reflection.Assembly]::LoadFile("$AI")
$InstrumentationKey = ""
$TelClient = New-Object "Microsoft.ApplicationInsights.TelemetryClient"
$TelClient.InstrumentationKey = $InstrumentationKey
$TrackMetric = New-Object "Microsoft.ApplicationInsights.DataContracts.MetricTelemetry"
$TrackMetric.Name = "PowershellTest"
$TrackMetric.Value = Get-Random -Minimum:1 -Maximum:100
$TelClient.TrackMetric($TrackMetric)
$TelClient.Flush()
Write-Output "Script End $TrackMetric.Value"
This PowerShell Script works, but after I moving that script to Runbook it is no longer working.
So, here is the issue.
I am not able to load the ApplicationInsight DLL inside the Runbook.
Any idea how to do that?
Exception Details
Exception calling "LoadFile" with "1" argument(s): "The system cannot find the file specified. (Exception from HRESULT:
0x80070002)"
Thanks
Siraj
Try following path for the assembly
"C:\Modules\Global\Azure\Compute\Microsoft.ApplicationInsights.dll"
The issue is in loading the DLL file. The Runbook is not able to find the file in this line:
$AI = "$PSScriptRoot\Microsoft.ApplicationInsights.dll"
[Reflection.Assembly]::LoadFile("$AI")
When you run a Runbook via Azure Automation, you don't have access to the local path as you normally do on a local machine or on premise. In Azure Automation, modules are placed in "C:\Modules".
Instead, use below code snippet, after you have uploaded the dll file:
[System.Reflection.Assembly]::LoadFrom("C:\Modules\Azure\Microsoft.ApplicationInsights.dll")
Closest Related Reference: Referencing DLL

How do I change the timeout value for Add-Blob Azure cmdlet?

I'm trying to invoke Add-Blob Azure cmdlet
Add-Blob -BlobType Block -FilePath $packagePath -ContainerName $blobContainerName
and it has been working just fine until recently but now it fails with
Operation could not be completed within the specified time.
message. I suspect that for whatever reason the upload speed has got really low and so it just doesn't manage to upload the file fast enough.
Is it possible to increase the timeout value for that operation?
Are you using the Cmdlets from http://wappowershell.codeplex.com? Please note that these cmdlets are now (kind of) deprecated and have been replaced by Windows Azure Management Cmdlets (http://msdn.microsoft.com/en-us/library/windowsazure/jj554330.aspx). Unfortunately, the cmdlet to add blob is not there in the new cmdlets.
Coming back to your question, I don't think it's possible to specify the request timeout with this Cmdlet and there's no source code available on CodePlex site for you to modify. What you could do is invoke Storage Client library directly through PowerShell. I took the liberty of modifying the code from this blog post (http://www.fsmpi.uni-bayreuth.de/~dun3/archives/uploading-a-file-to-azure-blob-storage-from-powershell/528.html) and included support for Timeout parameter there:
Add-Type -Path "C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\2012-06\ref\Microsoft.WindowsAzure.StorageClient.dll"
$accountName = "<your account name>";
$accountKey = "<your account key>";
$blobContainerName = "<your blob container name>";
$fullFilePath = "<Full path of the file you wish to upload>";
$requestTimeoutInSeconds = 600;
$cloudStorageAccountNameAndKey = new-object Microsoft.WindowsAzure.StorageCredentialsAccountAndKey($accountName, $accountKey);
$cloudStorageAccount = new-object Microsoft.WindowsAzure.CloudStorageAccount($cloudStorageAccountNameAndKey, $true);
$cloudBlobClient = [Microsoft.WindowsAzure.StorageClient.CloudStorageAccountStorageClientExtensions]::CreateCloudBlobClient($cloudStorageAccount)
$blobContainer = $cloudBlobClient.GetContainerReference($blobContainerName);
$blobContainer.CreateIfNotExist();
$blockBlob = $blobContainer.GetBlockBlobReference("<blob name>");
$blobRequestOptions = new-object Microsoft.WindowsAzure.StorageClient.BlobRequestOptions;
$blobRequestOptions.Timeout = [TimeSpan]::FromSeconds($requestTimeoutInSeconds);
$blockBlob.UploadFile($fullFilePath, $blobRequestOptions);
If you're looking for alternatives to Microsoft's PowerShell Cmdlets, may I suggest you take a look at Cerebrata Azure Management Cmdlets [I'm one of the devs for this product]. It has cmdlets for complete storage management and service management.
Hope this helps.