PS Azure automation runbook ; How to Mount Azure File Share? - azure

Trying to mount Azure FS from Powershell runbook in Azure Automation.
Via username and key
$UserName = "localhost\trex4xfs"
$Key = "Zav---mykey-----1Tdw=="
$RemotePath = "\\myshare.file.core.windows.net\mainfs"
$MapDrive = "z:"
Get-Command -Name *SmbMapping* | ft
[securestring]$pass = ConvertTo-SecureString $key -AsPlainText -Force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $pass
new-psdrive -name T -PsProvider FileSystem -root $RemotePath -credential $credential
Get-PSDrive | ft
echo "--------now import smb"
Import-Module smbshare
echo "--------now smb"
New-SmbMapping -LocalPath $MapDrive -RemotePath $RemotePath -UserName $UserName -Password $Key
Above works great on "plain Powershell on Windows"
Tried
Runbook with 5.1 and 7.1 PS version
new-psdrive (error: This function is not supported on this system )
New-SmbMapping (error 7.1: The 'New-SmbMapping' command was found in the module 'SmbShare', but the module could not be loaded. For more information, run 'Import-Module SmbShare'
New-SmbMapping (error 5.1: Cannot connect to CIM server. The specified service does not exist as an installed service. )
Import-Module smbshare (error Failed to generate proxies for remote module 'smbshare'. Cannot overwrite the item C:\Users\Client\Temp\tmp_5t22mi1k.oh0\remoteIpMoProxy_smbshare_2.0.0.0_localhost_f29e4e95-e8cf-4256-a4db-fc9381c6563c.format.ps1xml with itself.)
New-CimSession (error: The specified service does not exist as an installed service.)
Seem to be related to New-CimSession not available on Azure Automation runbook
other questions related to this:
Azure Runbook - Get a file from Azure File System Storage
Not able to access Azure FileShare Storage container from Azure Automation Runbook
Map a Azure Fileshare to Azure Runbook local drive to use as temporary storage

One of the related question which you have shared already provides the answer (i.e., this one) which basically says to use hybrid runbook worker in your use case scenario.

Related

vCenter logon failing using Get-VICredentialStoreItem from Azure automation runbooking with hybrid worker

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.

Connect-MgGraph in Azure Automation

I am currently busy to convert my Azure AD PowerShell scripts to Microsoft Graph PowerShell. I have already some scripts that I want to run within Azure Automation, but I try to figure out how to connect to Azure Automation.
With Azure AD PowerShell, I have a connected service account in Azure Automation. With Microsoft Graph PowerShell I'm trying to use a RunAs account within the Azure Automation Account with the following connection:
$Connection = Get-AutomationConnection -Name AzureRunAsConnection
# Get certificate from the automation account
$Certificate = Get-AutomationCertificate -Name AzureRunAsCertificate
# Connect to the Graph SDK endpoint using the automation account
Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connection.TenantId -CertificateThumbprint $Connection.CertificateThumbprint
When I run the RunBook to create the connection I get an error:
Connect-MgGraph: C:\Temp\os4k24vd.4cs\xxxxxxxxxxxxxxxxxxx.ps1:5
Line | 5 | Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connec …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0,
| Culture=neutral, PublicKeyToken=xxxxxxx'. The system cannot | find the file specified.
I have the following module installed that is needed for Connect-MgGraph Microsoft.Graph.Authentication >> Runtime: 7.1 When I search on the error, it have something to do that .NET could not find the Json.NET library. But which module I'm missing in Azure Automation, or are there other ways to connect Microsoft Graph PowerShell with Azure Automation?
I hope you are using App only Access approach to connect the Azure Automation. if not refer MSDOC - App only Authentication
To get the Certificate and AppID you can use the below command let
#To get App Id
$AppId = Get-AutomationVariable -Name '<Your AppID>'
# Get TenentId
$TenantId = Get-AutomationVariable -Name '< your tenantId>'
# Get Certificate
$CertificateName = Get-AutomationCertificate -Name '<Your Certificate>'
#Connect the mgGraph
Connect-MgGraph -ClientID $AppId -TenantId $TenantId -CertificateName $CertificateName ## Or -CertificateThumbprint
Still, you are facing issue please give a try Automation Hybrid Runbook Worker for more flexibility.
The problem was not the first connect script, but the runtime version. After changing to PS 5.1 instead of 7.1 it all works. The Runbook now shows 'Welcome to Welcome To Microsoft Graph!'
$Connection = Get-AutomationConnection -Name AzureRunAsConnection
# Connect to the Graph SDK endpoint using the automation account
Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connection.TenantId -CertificateThumbprint $Connection.CertificateThumbprint

Powershell Script continues to ask me to use Select-AzureSubscription although I have called it

I have an Azure runbook where I am trying to deallocate VMs. When I run the runbook I get the error
Stop-AzureVM : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to
set the default subscription.
I have used the below in my script.
Add-AzureRmAccount
Select-AzureRMSubscription
After calling the select, it prints out
PSComputerName : localhost
PSSourceJobInstanceId :
Account :
Environment :
Subscription :
Tenant :
with the correct subscrption and tenant information so it seems the select is working correctly, but for some reason I still cannot use the Stop-AzureVM cmdlet.
Any ideas?
The command Stop-AzureVM is Azure Service Management PowerShell command. It just can be used to stop Azure classic VM. But the command Add-AzureRmAccount is Azure Resource Management PowerShell command. After running the command, we just can manage Azure Resource Management resources. For more details, please refer to here and here.
So with Azure ARM VM, please use the command Stop-AzureRmVM to stop it. Meanwhile, regarding how to stop Azure classic VM, please refer to the following steps
Create Azure Classic Run As Account
Script
$ConnectionAssetName = "AzureClassicRunAsConnection"
# Get the connection
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
# Authenticate to Azure with certificate
$CertificateAssetName = $Conn.CertificateAssetName
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
#stop VM
Stop-AzureVM -ServiceName "ContosoService01" -Name "MyVM" -Force
Besides, regarding how to check if the VM is classic, please refer to the blog
Try Running the below :
Get-Module AzureRm.Profile -ListAvailable
This issue might occur when there is multiple instances of the module. If there are multiple instance remove the older modules and retain the new module.
To remove the old module : Uninstall-Module -Name AzureRm.Profile -RequiredVersion 4.6.0#(olderversion if you have any)

How to create a Microsoft Team using a Queue Triggered Azure Function writed in PowerShell?

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

How to stop all VMs with Azure Automation using Resource Manager module?

I have created some Azure VMs using the new Resource Manager and i'd like to stop them everyday.
To do so, i've published a runbook to stop aboth classic and ARM VMs, and i created a scheduler which runs the runbook every night :
workflow Stop-AzureVMs
{
$cred = Get-AutomationPSCredential -Name 'Cred'
Add-AzureAccount -Credential $cred
Select-AzureSubscription -Current 'SubscriptionName'
Get-AzureVM | Stop-AzureVM –Force
Get-AzureRmVM | Stop-AzureRmVM -Force
}
I have imported the AzureResourceManager module to my Azure Automation account :
But i am getting this error :
Exception
At line:34 char:2
+ Get-AzureRMVM | Stop-AzureRMVM -Force
+ ~~~~~~~~~~~~~ Cannot find the 'Get-AzureRMVM' command. If this command is defined as a workflow, ensure it is defined before the workflow that calls it. If it is a command intended to run directly within Windows PowerShell (or is not available on this system), place it in an InlineScript: 'InlineScript { Get-AzureRMVM }'
How is that possible ?
Edit : Below is the solution
$cred = Get-AutomationPSCredential -Name 'Cred'
Add-AzureRmAccount -Credential $cred
Select-AzureRmSubscription -Name 'SubscriptionName' -SubscipritionId 'SubscriptionId'
Get-AzureRmVM | Stop-AzureRmVM -Force
All workflows i found didn't mention the use of Add-AzureRmAccount and Select-AzureRmSubcription instead of the standard Add-AzureAccount and Select-AzureSubscription. I thought that the authentication process to our Azure account was the same.
Update : It is now possible to combine both ASM and ARM cmdlets within the same runbooks, see this post for more informations about ARM supported by default on Azure Automation
Looks like you imported the old version of the ARM cmdlets (before Azure PS 1.0) into Azure Automation. This was before the *-AzureRm* renaming. So tt should be Stop-AzureVM not Stop-AzureRmVM.
However, that makes it ambiguous as to whether you are trying to call Azure Service Management or Azure Resource Manager cmdlets -- which is exactly why the cmdlet names were renamed in Azure PS 1.0. I recommend you follow the guidance here.
As per my understanding ASM mode is default. If you are going for ARM command firstly switch mode is required using Switch-AzureMode
One more confusion is what is the purpose of Get-AzureRMVM command. I googled but coulndn't find anything -
The Get-AzureRMVM cmdlet is in the AzureRM.Compute module... The AzureRM* cmdlets are still in preview, I don't think they are available in Azure Automation yet.
The two modules in your screenshot above likely correspond to the 0.9.x version of the cmdlets and there were indeed two different modules (Azure=ASM and AzureResourceManager=ARM) behind Switch-AzureMode. Switch-AzureMode just unloads one and loads the other.
If Automation is still using the 0.9.x version of the cmdlets then you should be able to just use Get-AzureVM for ARM VMs using the AzureResourceManager module.
Below is the solution
$cred = Get-AutomationPSCredential -Name 'Cred'
Add-AzureRmAccount -Credential $cred
Select-AzureRmSubscription -Name 'SubscriptionName' -SubscriptionId 'SubscriptionId'
Get-AzureRmVM | Stop-AzureRmVM -Force
It is not yet possible to combine ARM and ASM cmdlets in same runbook apparently ... So you have to use only ARM cmdlet or ASM cmdlet.
Also, all workflows i found didn't mention the use of Add-AzureRmAccount and Select-AzureRmSubcription instead of the standard Add-AzureAccount and Select-AzureSubscription.
I thought that the authentication process to our Azure account was the same.
The Following code will work for both old style and new Style VM's but be aware this will shut down all machines with no warning.
{
# TODO: update to the name of the credential asset in your Automation account
$AutomationCredentialAssetName = "AzureAutomationRG"
# Get the credential asset with access to my Azure subscription
$Cred = Get-AutomationPSCredential -Name $AutomationCredentialAssetName
# Authenticate to Azure Service Management and Azure Resource Manager
Add-AzureAccount -Credential $Cred
Add-AzureRmAccount -Credential $Cred
"`n-Old Style VMS-`n"
# Get and output Azure classic VMs
$VMs = Get-AzureVM
$VMs.Name
Get-AzureVM | Stop-AzureVM -Force
"`n-New Style Resource Group VMs-`n"
# Get and output Azure v2 VMs
$VMsv2 = Get-AzureRmVM
$VMsv2.Name
Get-AzureRmVM | Stop-AzureRmVM -Force
}
For new Azure RM VMs use access extensions the following command:
Set-AzureRmVMAccessExtension -ResourceGroupName "ResourceGroupName" -VMName "VMName" -Username "Admin User Name" -Password "Admin Password" -Name "Extension Name"
Please note the -Name parameter is the arbitrary extension name.
This might be late to the party, but I would recommend you check out this link:
https://www.attosol.com/start-or-stop-all-vms-of-a-resource-group-in-azure/
Basically, you can create a script and write some aliases with switches to make your job super easy.

Resources