I am new to Azure Power shell and Azure functions.
I have requirement where I have to execute Powershell command to stop PostgreSQL replication
I created the Azure function app with default options and created the function. Inside the function I updated with Get-AzSubscription. I am getting error for all azure commands.
"Get-AzResource/Get-AzSubscription/Get-AzModule" is not recognized as a name of cmdlet or function or Scrip file or executable program
but I am able to execute the "Get-Date" and get required results
Please suggest how to fixes to this issue
Thanks in advance
Ramabadran
"Get-AzResource/Get-AzSubscription/Get-AzModule" is not recognized as a name of cmdlet or function or Scrip file or executable program
To run the PowerShell cmdlets on Azure PowerShell Runtime Stack Function App/Project, you need to uncomment the Az module in requirements.psd1 with the Az module version i.e., compatible with PowerShell Version you're using the Function App:
requirements.psd1:
#{
'Az' = '8.*'
}
run.ps1:
using namespace System.Net
param($Request, $TriggerMetadata)
Write-Host "PowerShell HTTP trigger function processed a request."
Connect-AzAccount -Tenant '<Azure-tenant-id>' -SubscriptionId '<Azure-Subscription-Id>'
$SubscriptionInfo = Get-AzSubscription -TenantId "<Azure-tenant-id>"
Write-Host $SubscriptionInfo
$body = "Hello Jahnavi, This HTTP triggered function executed successfully."
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Body = $body
})
Result:
Note: Also, Install the Azure modules in the Function app workspace of the VS Code Terminal using these cmdlets Install-Module Az, Import-Module Az.
Related
I'm having two runbooks of two different Powershell versions (5.1, 7.1). How to call a runbook (7.1) from runbook (5.1)?
Modules used:
AZ-SecurityInsights - 5.1 version (runbook 5.1)
AzSentinel - 7.1 version (runbook 7.1)
Need to pass resourcevariable as an input parameter to second runbook from first runbook.
My code:
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
Start-AzAutomationRunbook -AutomationAccountName $automationAccountName -Name "ExportAlertRule" -ResourceGroupName $automationResourceGroupName
Error:
Object reference not set to an instance of an object.
What can I try next?
If the output stream of Start-AzAutomationAccount contains object, the command does not process the output stream correctly. For the same, you need to implement a polling logic, and use the Get-AzAutomationJobOutput cmdlet to retrieve the output.
For more information, refer below documents.
https://learn.microsoft.com/en-us/azure/automation/troubleshoot/runbooks#resolution-13
https://learn.microsoft.com/en-us/azure/automation/automation-child-runbooks#runbook-types
I am having trouble creating a release definition on Azure DevOps. I believe the Register-Environment function in PowerShellOnTargetMachines.ps1 is failing:
try
{
$connection = Get-VssConnection -TaskContext $distributedTaskContext
Write-Verbose "Starting Register-Environment cmdlet call for environment : $environmentName with filter $machineFilter"
$environment = Register-Environment -EnvironmentName $environmentName -EnvironmentSpecification $environmentName -UserName $adminUserName -Password $adminPassword -WinRmProtocol $protocol -TestCertificate ($testCertificate -eq "true") -Connection $connection -TaskContext $distributedTaskContext -ResourceFilter $machineFilter
Write-Verbose "Completed Register-Environment cmdlet call for environment : $environmentName"
Write-Verbose "Starting Get-EnvironmentResources cmdlet call on environment name: $environmentName"
$resources = Get-EnvironmentResources -Environment $environment
if ($resources.Count -eq 0)
{
Write-Telemetry "Input_Validation" "No machine exists for given environment"
throw (Get-LocalizedString -Key "No machine exists under environment: '{0}' for deployment" -ArgumentList $environmentName)
}
$resourcesPropertyBag = Get-ResourcesProperties -resources $resources
}
With the following error (I have omitted some of my organization's information, but it is there and looks right):
2019-09-04T12:34:55.6886629Z ##[debug]VssConnection created
2019-09-04T12:34:55.7518340Z ##[debug]Starting Register-Environment cmdlet call for environment : [machine] with filter [machine]
2019-09-04T12:34:55.7843531Z ##[debug]Begin Create-Environment cmdlet
2019-09-04T12:34:55.7872731Z ##[debug]UserName=[username]
2019-09-04T12:34:55.7878292Z ##[debug]WinRmProtocol=HTTP
2019-09-04T12:34:55.7878658Z ##[debug]TestCertificate=False
2019-09-04T12:34:55.7878965Z ##[debug]Unable to create a environment object for given json - Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
2019-09-04T12:34:55.7879241Z ##[debug]projectName=[projectName]
2019-09-04T12:34:55.7879517Z ##[debug]Getting environment [machine] from DTL Service
2019-09-04T12:34:55.8485808Z ##[debug]Processed: ##vso[task.logissue type=error;code={"Task_Internal_Error":Page not found.};]
And I do not know what to do. Any ideas are appreciated. Thanks for taking the time to read my question.
Based on the details which from comment that Mike left, the issue should caused by the the task version you are using and its feature script we defined.
According to the ticket description you raised in DC ticket:
I am trying to use V2 of the following 'PowerShellOnTargetMachines'
PowerShell script for a release on azure devops, from
azure-pipeline-tasks.
the version of PowerShellOnTargetMachines you are using is 2.*.
We can get the Register-Environment cmdlet script with decompile tool follow the method I showed in this case.
You can see the parameters this cmdlet supported in 'PowerShellOnTargetMachines V2.*' does not include TaskContext and Connection. That's why you receive the error message "Unable to create a environment object for given json - Unexpected character encountered while parsing value". Because the parameter you input in the task does not match the configuration of Register-Environment cmdlet.
You can try with PowerShellOnTargetMachines V1.*. In 1.* we support the parameters TaskContext and Connection.
I am working on a SSAS Tabular project in Visual Studio 2017 where I want to automate build and deploy (and testing) locally and in azure analysis services. The project is connected to an Azure Devops project and it works.
But I am struggling a lot when it comes to build and deploy the project in azure devops. I have followed a blog on this topic (https://notesfromthelifeboat.com/post/analysis-services-1-deployment/) and author has created some powershell scripts that works on my computer when I am running them locally on Windows Powershell ISE. But when I tried to create a build pipeline on devops using the same Powershell file in a Powershell task it fails. I created some variables and set a reference to the powershell file. So far so fine.When I tried to run the build I got an error saying:
Import-Module : The specified module 'SqlServer' was not loaded
because no valid module file was found in any module
It seems that powershell in devops are not able to load the Import-Module -Name SqlServer. I have searched on the net for a solution but nothing has worked so far, and other combination of the ImpI have discovered that there is a small difference in the $env:PSModulePath environment variable between in Powershell ISe and in the Powershell ci-build task, but I am not sure if that is the problem.
If any of you have experience knowing how to solve this issue or have a better solution on how to deploy SSAS Tabular model locally and especially deploying to azure (may be some of you have experience with automation) from build/release.
build setup on devops
Error from running the build
Powershell script
Command: .\deploy_model.ps1 -workspace c:\develop\tabular-automation -environment validation -analysisServicesUsername test_ssas -analysisServicesPassword test_ssas
param(
[Parameter(Mandatory)]
[string]$workspace,
[Parameter(Mandatory)]
[string]$environment,
[Parameter(Mandatory)]
[string]$analysisServicesUsername,
[Parameter(Mandatory)]
[string]$analysisServicesPassword,
[string]$databaseServer = "localhost",
[string]$analysisServicesServer = "localhost"
)
Import-Module -Name SqlServer
$ErrorActionPreference = "Stop"
# Build the model
$msbuild = 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe'
& "$msbuild" TabularExample.smproj "/p:Configuration=$environment" /t:Clean,Build /p:VisualStudioVersion=14.0
# Copy build outputs and deployment options to deployment directory
$deploymentDir = ".\deployment"
mkdir -Force $deploymentDir
cp "bin\$environment\*.*" $deploymentDir
cp .\deploymentoptions\*.* $deploymentDir
# Update deployment targets with parameters
$template = Get-Content .\deploymentoptions\Model.deploymenttargets
$expandedTemplate = $ExecutionContext.InvokeCommand.ExpandString($template)
$expandedTemplate | Set-Content "$deploymentDir\Model.deploymenttargets"
# Create the deployment script
Microsoft.AnalysisServices.Deployment.exe "$deploymentDir\Model.asdatabase" /s:"$deploymentDir\deploy.log" /o:"$deploymentDir\deploy.xmla" | Out-Default
# Deploy the model
$SECURE_PASSWORD = ConvertTo-SecureString $analysisServicesPassword -AsPlainText -Force
$CREDENTIAL = New-Object System.Management.Automation.PSCredential ($analysisServicesUsername, $SECURE_PASSWORD)
Invoke-ASCmd –InputFile "$workspace\$deploymentDir\deploy.xmla" -Server $analysisServicesServer -Credential $CREDENTIAL
For third party modules, or solution has been to modify the $env:PSModulePath to point to a network location that has the version of the module we want our build agents to run. I use code like below (We also set the PSModulePath to the relative path to our custom modules that are stored in the same repo, but I removed that part of code since you do not state that you have any custom modules)
I like this better than constantly running Install-Module because I have better control over what version of the modules are running, and I do not have to worry about having our build boxes constantly communicating with PowershellGallery
try {
Import-Module SQLServer -Force -ErrorAction Stop
}
catch {
$networkPath = "\\Network path to Modules\"
if (!(Test-Path $networkPath)) {
Write-Error "Can not set env:PSModulePath to the published location on the network" -ErrorAction Stop
}
else {
if (!($env:PSModulePath -like "*;$networkPath*")) {
$env:PSModulePath = $env:PSModulePath + ";$networkPath"
}
}
}
else {
Write-Host "Setting the modulePath to $modulePath"
if (!($env:PSModulePath -like "*;$modulePath*")) {
$env:PSModulePath = $env:PSModulePath + ";$modulePath\"
}
}
Import-Module SQLServer -Force -DisableNameChecking -ErrorAction Stop
}
I am attempting to login to an Azure account through a PowerShell script by means of making use of a publishsettings file; However, I am still finding that it is requiring me to login to my account using Login-AzureRmAccount, regardless of having those credentials.
My step-by step looks something like this:
Clear out all accounts that may be available:
Get-AzureAccount | ForEach-Object { Remove-AzureAccount $_.ID -Force }
Download the PublishSettings file: Import-AzurePublishSettingsFile –PublishSettingsFile $PublishSettingsFileNameWithPath
Select the Azure subscription using the subscription ID:
Select-AzureRMSubscription -SubscriptionId $SubscriptionId
And finally, create a new resource group in the subscription before deploying it: New-AzureRmResourceGroup -Name $ResourceGroupName -Location $ResourceGroupLocation -Verbose -Force 2>> .\errorCIMS_RG.txt | Out-File .\rgDetailsCIMS_RG.txt
However, this is when an error is thrown: Run Login-AzureRmAccount to login.
Assuming I have the PublishSettings file, and it hasnt expired, why would this be giving back an error?
As Mihail said, we should check Azure PowerShell version first, and install the latest version.
We can run this command to list Azure PowerShell version:
Get-Module -ListAvailable -Name Azure -Refresh
By the way, Import-AzurePublishSettingsFile work for ASM, New-AzureRmResourceGroup is ARM command, so if you want to create resource group, you should Login-AzureRmAccount first.
Note:
The AzureResourceManager module does not support publish settings
files.
More information about Import-AzurePublishSettingsFile, please refer to this link.
I solved this problem by updating to last version of azure powershell cmdlet.
You can find last one here:
https://github.com/Azure/azure-powershell/releases
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.