Code That I am running on azure portal
Write-Output "Starting"
$assemblyPath = "C:\Modules\Global\Azure\Compute\Microsoft.Exchange.WebServices.dll"
dir $assemblyPath
Write-Output "1"
Add-Type -Path $assemblyPath
Write-Output "2"
Output
Any idea on this?
To load the .dll assembly, you could refer to the steps.
1.Navigate to your automation account in the portal-> Modules -> Add Module, compress the Microsoft.ApplicationInsights.dll file to Microsoft.ApplicationInsights.zip, then upload. After uploading, you will find it in the portal.
2.Change the $assemblyPath, your complete command should be as below, it will work fine.
Write-Output "Starting"
$assemblyPath = "C:\Modules\User\Microsoft.ApplicationInsights\Microsoft.ApplicationInsights.dll"
dir $assemblyPath
Write-Output "1"
Add-Type -Path $assemblyPath
Write-Output "2"
Output:
Related
We are using Azure automation runbook using hybrid worker and trying to collect information from on-prem vcenter environment. We are using Get-VICredentialStoreItem to logon to vcenter but logon itself using stored credentials is failing from runbook. When I use this script locally on hybrid worker server it works fine.
The error we are getting is that it can't find the path(most likely for xml file) so it can't logon to vcenter server. Screenshot of error is below.
My understanding is that the script runs locally in hybrid worker server so if it is not complaning about path locally then why would this be causing an issue while running from runbook hybrid worker.
$date = get-date -format dd-MM-yyyy
#Load Module and connect to vCenter
Get-Module -Name VMware.PowerCLI.VCenter* -ListAvailable | Import-Module
Get-Module -Name VMware.Sdk* -ListAvailable | Import-Module
Get-Module -Name VMware.VimAutomation.Core | Import-Module
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
Set-PowerCLIConfiguration -Scope User -ParticipateInCEIP $false -Confirm:$false
$Credentials = Get-VICredentialStoreItem -Host "server1.domain.local" -File "\\mgmtserver.domain.local\Credentials\pwd.xml"
Connect-viserver -server "server1.domain.local" -User $Credentials.User -Password $Credentials.Password
$datastore = "\\mgmtserver.domain.local\myshare2\VMware-Corp-Datastores.csv"
#add VMtools details
New-VIProperty -Name ToolsVersion -ObjectType VirtualMachine -ValueFromExtensionProperty 'Config.tools.ToolsVersion' -Force
New-VIProperty -Name ToolsVersionStatus -ObjectType VirtualMachine -ValueFromExtensionProperty 'Guest.ToolsVersionStatus' -Force
#export datastore list
get-datastore | Select Name, Datacenter, CapacityGB, FreeSpaceGB | export-csv $datastore -NoTypeInformation -UseCulture
disconnect-viserver -Server * -confirm:$false
Error screenshot
The system cannot find the path specified.
A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Please specify server credential
Found the issue, credentials have to be created using same account that is going to use it in Automation account.
I'm trying to take specific configuration backup in Azure webapp wwwroot folder with below powershell script which was working fine in public App service plan(Standard and Premium) but the same powershell script is not working fine in Private App service plan(Isolated(App service Environment) - I1,I2,I3). Please find the code below.
Code:
Import-Module Kudu-api
$userNm="`$Testapp"
$password="*******"
$token = New-KuduAuthorizationToken $userNm $password
$sitename="Testapp"
Set-Location "C:\Users\admin\Desktop\Backups"
sleep -Seconds 2
Receive-KuduFile $sitename $token '/site/wwwroot/appsettings.json' ./appsettings.json`
Getting the below error when trying the above script in Isolated(I1) appservice plan:
Error : Invoke-RestMethod : The remote name could not be resolved: 'Testapp.scm.azurewebsites.net'
Please suggest how we can resolve this.
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 want to deploy app services from Powershell.
I would like to use only publish profile (no password for azure account).
I tried FTP service, but sometimes files are blocked by running users.
I think I have to stop app service.
There is powershell command like:
Publish-AzWebApp
However first I need login with:
Connect-AzAccount
and pass credentials what I want to avoid.
There is any way to call Publish-AzWebApp based on only publish profile (no login by account)?
Connect-AzAccount has other options to login (token or certificate).
Unfortunately I don't know how to generate it.
BTW There was a topic about it:
How do I deploy to Azure App Service with PowerShell?
But it is old and now module "az" is recommended.
There is any way to call Publish-AzWebApp based on only publish profile (no login by account)?
No, you can't. If you want to use the Publish-AzWebApp , you always need to login with Connect-AzAccount, whatever the parameters you use, examples here.
If you want to use powershell to deploy the web app based on only publish profile, the workaround is to use Kudu API via powershell.
$username = "`$webappname"
$password = "xxxxxxx"
# Note that the $username here should look like `SomeUserName`, and **not** `SomeSite\SomeUserName`
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$userAgent = "powershell/1.0"
$apiUrl = "https://joywebapp.scm.azurewebsites.net/api/zipdeploy"
$filePath = "C:\Users\joyw\Desktop\testdep.zip"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST -InFile $filePath -ContentType "multipart/form-data"
You may refer to this tutorial: https://learn.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-2.5.0#sign-in-with-a-service-principal-
Here is the step by step process of deploying and publishing an Azure app service with PowerShell (PS) using newly recommended Az module. You'll have to install Azure CLI before running the scripts:
$subscription = 'Visual Studio Enterprise – MPN' #Change it as per your Azure subscription
$location = 'Central US' #Change it according to the location where you want to host your web app
$resourceGroup = 'MyWebAppResourceGroup'
$ErrorActionPreference = "Stop" #this ensures that script stops executing at first error in the script.
Write-host "Installing nuget package provider"
Install-PackageProvider -Name NuGet -Scope CurrentUser -MinimumVersion 2.8.5.201 -Force
Write-Host "Setting Power Shell gallery"
Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
Write-Host "Installing missing PowerShell modules required for running this script.."
if ((Get-InstalledModule -Name "Az.Accounts" -ErrorAction SilentlyContinue) -eq $null) {
Write-Host "Az.Accounts module missing. Now installing..."
Install-Module -Name Az.Accounts -Scope CurrentUser
}
if ((Get-InstalledModule -Name "Az.Websites" -ErrorAction SilentlyContinue) -eq $null) {
Write-Host "Az.Websites module missing. Now installing .."
Install-Module -Name Az.Websites -Scope CurrentUser
}
Write-Host "Installing PowerShell modules completed."
Write-Host "Staring to import PowerShell modules in current session...."
Import-Module Az.websites
Write-Host "Importing PowerShell modules completed."
#This is required due to an issue due to which PowerShell fails to connect with online resources. This issue is machine specific. So you can comment it if not required.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Write-Host "Connecting to Azure account..."
Connect-AzAccount
Write-Host "Setting subscription for current session..."
az account set --subscription $subscription
Write-Host "Creating resource group..."
az group create --name $resourceGroup --location $location
$webAppName="WelcomeCloudApp"
$appServicePlan="WelcomeCloudAppServicePlan"
Write-Host "Creating WebApp Service plan..."
New-AzAppServicePlan -Name $appServicePlan -ResourceGroupName $resourceGroup -Location $location -Tier 'Free' #-Debug
Write-Host "Creating WebApp..."
New-AzWebApp -Name $webAppName -Location $location -AppServicePlan $appServicePlan -ResourceGroupName $resourceGroup
Write-Host "Publishing WebApp..."
Publish-AzWebApp -ResourceGroupName $resourceGroup -Name $webAppName -ArchivePath WelcomeCloudAppService.zip
Write-Host "Finished installing your web app. Bye!"
I would like to know how to create an alert for an Azure VM which tells me if the server(s) is running at a specific time.
The scenario:
Servers for the Azure network need to start at 7:30am to be ready for the users as they shut down at 7:30pm each day to save $$.
Today the azure automation script could not find any vms for the resource group! So that meant the servers where not started. I want to create an alert that will only tell me if the server(s) are not running at say 7:45am. So I can start them.
(Running the script now does find all of the servers now but didn't before for some reason... maybe Azure was moving the vms in the resource group?)
I have looked at:
- Microsoft Operations Management Suit > Log Search > Add Alert Rule.
- Resource Manager > Virtual Machines > Monitoring > Alert Rules > Add metic alert & Add activity log alert.
But I can't see where to only run the alert at a specific time.
Update/Edit:
Script used:
param (
[Parameter(Mandatory=$false)]
[String]$AzureCredentialAssetName = 'AzureCred',
[Parameter(Mandatory=$false)]
[String]$AzureSubscriptionIDAssetName = 'AzureSubscriptionId'
)
# Setting error and warning action preferences
$ErrorActionPreference = "SilentlyContinue"
$WarningPreference = "SilentlyContinue"
# Connecting to Azure
$Cred = Get-AutomationPSCredential -Name $AzureCredentialAssetName -ErrorAction Stop
$null = Add-AzureAccount -Credential $Cred -ErrorAction Stop -ErrorVariable err
$null = Add-AzureRmAccount -Credential $Cred -ErrorAction Stop -ErrorVariable err
# Selecting the subscription to work against
$SubID = Get-AutomationVariable -Name $AzureSubscriptionIDAssetName
Select-AzureRmSubscription -SubscriptionId $SubID
# Getting all resource groups
$ResourceGroup = "Servers"
# Getting all virtual machines
$RmVMs = (Get-AzureRmVM -ResourceGroupName $ResourceGroup -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).Name
# Managing virtual machines deployed with the Resource Manager deployment model
"Loop through all VMs in resource group $ResourceGroup."
if ($RmVMs)
{
foreach ($RmVM in $RmVMs)
{
"`t$RmVM found ..."
$RmPState = (Get-AzureRmVM -ResourceGroupName $ResourceGroup -Name $RmVM -Status -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).Statuses.Code[1]
if ($RmPState -eq 'PowerState/deallocated')
{
"`t$RmVM is starting up ..."
$RmSState = (Start-AzureRmVM -ResourceGroupName $ResourceGroup -Name $RmVM -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).IsSuccessStatusCode
if ($RmSState -eq 'True')
{
"`t$RmVM has been started."
}
else
{
"`t$RmVM failed to start."
}
}
}
}
else
{
"No VMs for $ResourceGroup deployed with the Resource Manager deployment model."
}
"Runbook Completed."
I just want a fail safe to know if the servers are not running when they should be.
Expected output:
Loop through all VMs in resource group Servers.
DOMAINCONTROLLER found ...
SQLSERVER found ...
GATEWAY found ...
APPLICATIONHOST found ...
Runbook Completed.
instead of:
Loop through all VMs in resource group Servers.
No VMs for Servers deployed with the Resource Manager deployment model.
Runbook Completed.
I.e. rerunning the same script manually gave expected results.
Based on my knowledge, Azure metric alert could not send mail when your VM has been started or stopped at a specific time.
According to your description, Start/Stop VMs during off-hours [Preview] solution in Automation is a good solution for you to save money.
The Start/Stop VMs during off-hours [Preview] solution starts and stops your Azure Resource Manager virtual machines on a user-defined schedule and provides insight into the success of the Automation jobs that start and stop your virtual machines with OMS Log Analytics.
It could send email notifications when the start and stop VM runbooks complete.
You also could use Azure automation to start or stop VM for a specific time, more information please refer to this link.
Update:
Your script works for me. I check your script, $RmVMs = (Get-AzureRmVM -ResourceGroupName $ResourceGroup -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).Name returns null. Do you have multiple subscriptions? It seems that your subscription ID is wrong. Please ensure your subscription ID is right. You could get your subscription ID on your local PowerShell.
Get-AzureRmSubscription
Update2:
You could save your save your subscription to automation connection. You could use the script below:
param (
[Parameter(Mandatory=$false)]
[String]$AzureCredentialAssetName
)
# Authenticate to Azure with certificate
Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$connectionName = Get-AutomationConnection -Name $AzureCredentialAssetName
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $AzureCredentialAssetName
"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
throw $_.Exception
}
}
$ResourceGroup = "shui2"
.....