I want to use the following code in a Azure Function powershell app:
Add-AzTableRow `
-table outputTable`
-partitionKey $partitionKey `
-rowKey ($record.id) -property #{"userId" = "001";}
I'm using this documentation as a guide. However, this guide uses Install-Module AzTable. Since I am using a Function App to run this code on a timer, I can't install the module on run time. I've followed this question/answer. I've added this to `requirements.psd1':
#{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'.
# To use the Az module in your function app, please uncomment the line below.
#'Az' = '8.*'
AzTable = '2.*'
}
When I run the code I get the following error:
[Error] ERROR: The 'Add-AzTableRow' command was found in the module 'AzTable', but the module could not be loaded. For more information, run 'Import-Module AzTable'.
Could someone please give me some insight on what I'm doing wrong? I want to be able to update and query the table from the Function App without any user input.
Edit:
I have added 'Az' = '8.*' and 'AzTable' = '2.*'. I let the function install the resource by running and waiting. I'm now getting the error:
[Error] ERROR: The term 'Add-AzTableRow' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I'm not sure why I'm getting this error because Add-AzTableRow is apart if the AzTable module.
The AzTable module requires the Az Module:
It requires latest PowerShell Az module installed
https://www.powershellgallery.com/packages/AzTable/2.0.1
But currently the install of the Az module is disabled in your requirements.psd1:
Remove # from #'Az' = '8.*' = 'Az' = '8.*'
After that the machine behind the function will install the required module and the code will be able to load it/acces the functions.
Note if you "activate" a module the first time, run your code and maybe you still get the error messge -> script got started before module install completed... so simply wait some minutes and retry.
Run VS Code as an Administrator. Open the Azure PowerShell Functions Project in the VS Code.
In the VS Code Terminal of project Workspace/Path, run the below cmdlets one by one:
Install-Module Az
Import-Module Az
Install-Module AzTable -Force
Import-Module AzTable
Created Azure Functions PowerShell HTTP Trigger Function and written the code with the reference of this MS Doc:
run.ps1
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
# Interact with query parameters or the body of the request.
Connect-AzAccount -Tenant '<Tenant-Id>' -SubscriptionId '<Subscription-Id>'
Set-AzContext -Subscription "<Subscription-Id>"
$resourceGroup = "HariTestRG"
$storageAccountName ="store365rvi7b3lmoq"
$storageAccount=Get-AzStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccountName
$ctx = $storageAccount.Context
Write-Host $ctx.ConnectionString
$tableName = "pshkrishtesttable"
$cloudTable = (Get-AzStorageTable –Name $tableName –Context $ctx).CloudTable
Write-Host $cloudTable.Name
$partitionKey1 = "partition2"
Write-Host "Partition Key"
# add a row
Add-AzTableRow `
-table $cloudTable `
-partitionKey $partitionKey1 `
-rowKey ("India") -property #{"username"="Jashu";"userid"=598}
Write-Host "Table Row Added"
$TableRows = Get-AzTableRow -table $cloudTable
Write-Host $TableRows | Format-Table
$body = "Hello Krishna, This HTTP triggered function executed successfully."
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Body = $body
})
requirements.psd1:
#{
'Az' = '8.*'
'Az.Storage' = '4.10.0'
'AzTable' = '2.1.0'
}
Result:
Note: If you are running the PowerShell Function with these modules for the first time, it will take some time during the runtime/execution.
Related
We are moving a few Azure Automation Hybrid-worker scripts to PowerShell 7.1. In doing so one of the commands that work in PowerShell 5.1 is: [PSCredential] $AutomationCredential = Get-AutomationPSCredential -Name 'abcdef'. When we try the same command in PowerShell 7.1 we get an error The 'Get-AutomationPSCredential' command was found in the module 'Orchestrator.AssetManagement.Cmdlets', but the module could not be loaded. For more information, run 'Import-Module Orchestrator.AssetManagement.Cmdlets'
We have added the Import-Module to the code but we get Could not load file or assembly 'JobRuntimeData.Client, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
We do find Orchestrator.AssetManagement.Cmdlets the on the hybrid-worker, in the sandbox area. We know that this module is loaded when the hybrid-worker is installed (https://learn.microsoft.com/en-us/azure/automation/shared-resources/modules#internal-cmdlets).
Based on the Microsoft official document
The 'Get-AutomationPSCredential is currently supported till Azure powershell 6.6.0
NOTE: Powershell 7.1 is still in preview so this may be the reason for the error .
Please refer this MS DOC for more information.
We are assuming the Orchestrator.AssetManagement.Cmdlets is bugged at this point, but have not found anything to say that it is. To get around it we were going to use a runbook variable to store the password, but it needs the cmdlet to actually decode a secret/hidden value.
In the end, we used a key vault to store the password. The following is what was used as a workaround.
$User = "AutomationUser"
$KeyVaultName = "KeyVault"
try {
$Password = (ConvertTo-SecureString (Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $User -AsPlainText) -AsPlainText -Force)
[PSCredential] $AutomationCredential = New-Object System.Management.Automation.PSCredential($User, $Password)
}
catch {
$ErrorMessage = "Unable to retrieve credentials for user: [${$User}]. $_"
throw $ErrorMessage
BREAK
}
I have a linux Cent OS vm and am trying to add a custom script to it. If i do it manually from the portal i am able to install the custom script extension for linux. But i am not able to install the custom script via powershell code that i added below. Need some help on it. I am storing the custom script file in a storage account and calling it from there when installing the custom script extension on Linux.
Error i get is : Enable failed: processing file downloads failed: failed to download file[0]: failed to download file: unexpected status code: actual=404 expected=200
if($vmname.OSType -eq "Linux"){
$resourcegroup=$vmname.ResourceGroupName
$location=$vmname.Location
$vm=$vmname.Name
$TheURI = "https://storageaccount.blob.core.windows.net/container/cstmscript.sh"
$ScriptSettings = #{"fileUris" = #($TheURI); "commandToExecute" = "sh cstmscript.sh";}
Set-AzVMExtension -ResourceGroupName $resourcegroup -VMName $vm -Name "Custom Script" -Publisher "Microsoft.Azure.Extensions" -TypeHandlerVersion 2.0 -ExtensionType "CustomScript" -Location $location -Settings $ScriptSettings
}
Cant use Set-AzVMCustomScriptExtension as that's for only Windows VM's
Thanks Satya It did work Btw . I needed to add the access keys.
here is the code
if($vmname.OSType -eq "Linux"){
$resourcegroup=$vmname.ResourceGroupName
$location=$vmname.Location
$vm=$vmname.Name
$TheURI = "https://storage.blob.core.windows.net/container/cstmscript.sh"
$ScriptSettings = #{"fileUris" = #($TheURI); "commandToExecute" = " sh cstmscript.sh";}
$ProtectedSettings = #{"storageAccountName"="storage";"storageAccountKey" = ""};
Set-AzVMExtension -ResourceGroupName $resourcegroup -VMName $vm -Name "Custom Script" -Publisher "Microsoft.Azure.Extensions" -TypeHandlerVersion 2.0 -ExtensionType "CustomScript" -Location $location -Settings $ScriptSettings -ProtectedSettings $ProtectedSettings
}
I had tried hitting the above the url
https://storageaccount.blob.core.windows.net/container/cstmscript.sh
Which is more or less 404 error as encountered below :
Enable failed: processing file downloads failed: failed to download file[0]: failed to download file: unexpected status code: actual=404 expected=200
Looks like you re not able to access the cstmsscript.sh & encountering a 404 - you will have to host the file anonymously accessible or alternatively use means to grant access ( like SAS )
I have created a Runbook and added below cmdlet
Get-AzFunctionApp | Stop-AzFunctionApp
I get below error
The term 'Get-AzFunctionApp' is not recognized as the name of a cmdlet,
I have imported all the below modules but no luck
After adding 'Az.Functions' I get below error
Failed
Cannot validate argument on parameter 'SubscriptionId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. (The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.)
The cmdlet Get-AzFunctionApp / Stop-AzFunctionApp are included in this module: Az.Functions.
Please import this module and then the functions related operation will work.
Here is an example(please note that add the -Force parameter for Stop-AzFunctionApp), it works as per my testing:
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
Get-AzFunctionApp -ResourceGroupName xxx | Stop-AzFunctionApp -Force
From the screenshot you posted, it looks like you are missing the Az.Functions module that contains both the Get-AzFunctionApp and Stop-AzFunctionApp cmdlets.
To import Az.Functions module into your Automation account, do the following:
From your Automation account, under Shared Resources, select Modules.
Select Browse Gallery.
In the search bar, enter the module name (Az.Functions).
On the PowerShell Module page, select Import to import the module into your Automation account.
You can also import the module through the PowerShell Gallery. Choose the Azure Automation tab and select Deploy to Azure Automation from here: Az.Functions.
I want to create a Team by using an azure function triggered by an Azure Queue.
Unfortunetly when I run the code it is not working inside the Azure Function.
I'm wondering. Is there a way to create a Microsoft Team using PowerShell inside an Azure Function ?
Import-module MicrosoftTeams
$group = New-Team -MailNickname "teamTitle" -displayname "teamTitle" -Visibility "private"
Add-TeamUser -GroupId $group.GroupId -User "user#etc.com"
New-TeamChannel -GroupId $group.GroupId -DisplayName "General"
Working locally. Not working within the Azure Function.
Bellow the error i'm getting :
ERROR: Import-Module : The specified module 'MicrosoftTeams' was not loaded because no valid
module file was found in any module directory. At D:\home\site\wwwroot\CreateTeam\run.ps1:3
char:1 + Import-Module MicrosoftTeams + [...]
Thank you
Based on the error message, your Function app does not have the MicrosoftTeams module installed. You need to include a reference to this module to the requirements.psd1 file (see https://learn.microsoft.com/azure/azure-functions/functions-reference-powershell#dependency-management for more details).
Currently this module is not yet natively integrated into the azure functions under powershell
To see all the available packages go in App Service -> Advanced Tools -> DebugConsole -> Powershell and run :
Write-Output ‘Getting PowerShell Module’
$result = Get-Module -ListAvailable |
Select-Object Name, Version, ModuleBase |
Sort-Object -Property Name |
Format-Table -wrap |
Out-String
Write-output `n$result
To manually add a package, It is necessary to create a directory "Module" At the same level as the directory of the function, They will be automatically preloaded.
(https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-powershell step "Function app-level Modules folder")
After installation of the module. use below code in your script to automate the process.
$securedpassword = ConvertTo-SecureString $Password -AsPlainText -Force
$mycredentials = New-Object System.Management.Automation.PSCredential ($Username, $securedpassword )
$res = Connect-MicrosoftTeams -Credential $mycredentials
I need to connect to AD in azure function app using powershell script. (as it is in function i need to do it without prompt)
I am trying this:
# Import AzureAD
Import-Module "D:\home\site\modules\AzureAD.psd1" -ErrorAction SilentlyContinue
$appId = "myAppId"
$thumb = "certThumb"
$tenantId = "myTenantId"
Connect-AzureAD -TenantId $tenantId -ApplicationId $appId -CertificateThumbprint $thumb
Unfortunately i am getting following error:
The term 'Connect-AzureAD' is not recognized as the name of a cmdlet, function, script file, or operable program.
I copied azureAd modules to fs of the function app, but it still looks like importing it doesn't give any result.
Do you know a way to solve it?
Using the AzureAD module in Azure Functions requires a workaround now: https://github.com/Azure/azure-functions-powershell-worker/issues/232#issuecomment-536744760
This will probably be fixed soon.
By the way, instead of copying the module into your app, consider using the Managed Dependencies feature