Azure Automation to run Sharepoint Online PowerShell Set-Commands - azure

I have set up Azure Automation Runbook to run PowerShell which interacts with Sharepoint Online. I'm using 2 modules; Microsoft.Online.SharePoint.PowerShell and AzureAD. I have same versions in my local machine. Also I have specified credentials for Azure Automation, and those are the same credentials I run on my local machine. For some reason Azure Automation Runbook doesn't execute Set- Commands. If I run the script on my local machine Set-Commands are executed just fine.
$myCred = Get-AutomationPSCredential -Name 'test'
$adminSiteUrl = "https://mytenant-admin.sharepoint.com"
# Connect to SPOService
Connect-SPOService -Url $adminSiteUrl -Credential $myCred
Get-SPOSite -Identity https://mytenant-my.sharepoint.com | select sharingcapability
Set-SPOSite -Identity https://mytenant-my.sharepoint.com -SharingCapability ExternalUserSharingOnly
Get-SPOSite is executed and written in output, butSet-SPOSite doesn't do anything. I've set Sharepoint External sharing settings from Sharepoint Admin Center UI to Allow SharePoint shares to ExternalUserSharing only and OneDrive shares to disabled. Set-SPOSite should change OneDrive sharingcapability to ExternalUserSharing only but it doesn't.
Azure Automation doesn't throw any errors and completes the script successfully. I also tried Set-SPOUser cmdlet to modify Site's IsSiteCollectionAdmin -property from test user just to test whether it works or not. Once again it worked fine from my local machine but not on Azure Automation Runbook.
UPDATE: I tried to implement same script in Azure Function and it behaves exactly same as Azure Automation Runbook. I installed same modules as I'm using in Azure Automation, nothing more. And still no errors in output.

Related

Set-AzContext authentication inside a runbook run on Hybrid Worker works only a few times, eventually fails

Instead of using Connect-AzAccount, I'm using a profile saved locally on my Hybrid Worker
to authenticate against Azure and loading it each time I run a runbook.
This approach works, but after 2 or 3 successful runs, all the following runbook jobs end up in Suspended state.
Unfortunately, jobs stop working so randomly that I just can't pinpoint a possible cause.
The auth code inside the runbook:
$profile = Import-AzContext -path $path
$subscriptionID = $profile.Context.Subscription.SubscriptionID
Set-AzContext -subscriptionID $subscriptionID
Running Get-AzContext locally confirms that the credentials & context are loaded, but Microsoft-SMA logs show an auth error (407 proxy).
Is there maybe a scope that I should set? Expiration time that I don't know about?
Should I maybe clear the context after each job run?
Any input would be appreciated.
Start by running Clear-AzContext at the beginning of your runbook to ensure any inherited contexts are cleared, or Disconnect-AzAccount at the end of your runbook. Per Microsoft:
By default, the Azure contexts are saved for use between PowerShell sessions. It is possible that when a previous runbook on the Hybrid Runbook Worker has been authenticated with Azure, that context persists to the disk in the System PowerShell profile, as per Azure contexts and sign-in credentials | Microsoft Docs. For instance, a runbook with Get-AzVM can return all the VMs in the subscription with no call to Connect-AzAccount, and the user would be able to access Azure resources without having to authenticate within that runbook. You can disable context autosave in Azure PowerShell, as detailed here.
If that doesn't resolve the issue I would enable Progress logging and step through the runbook to identify which part is causing the issue.

Azure Automation - Run scripts using Azure commands or PowerShell commands

I am looking to port production jobs into Azure automation. The goal would be to schedule maintenance from scripts held in a shared drive on all computers in that domain. Using Azure, I could use the Invoke-AzVMRunCommand cmdlet to accomplish this task. Powershell also natively supports running scripts remotely with the Invoke-Command cmdlet.
Is there any particular benefit in using one cmdlet as opposed to another? Invoke-Command assumes you have open communication with the target host, but that is a given in my case. Are there any other drawbacks to using Invoke-Command? What about Invoke-AzVMRunCommand?
From Azure portal if we want to run any powershell script inside an Azure VM, we use this Invoke-AzVMRunCommand cmdlet, there it will open the Powershell window to connect to the Azure VM from backend.
The Run Command option is recommended if you need to run scripts inside an Azure VM using the guest agent.
You can also run this command directly from Azure PowerShell, CLI and Cloud Shell as well.
Invoke-AzVMRunCommand -ResourceGroupName '<myResourceGroup>' -Name '<myVMName>' -CommandId 'RunPowerShellScript' -ScriptPath '<pathToScript>' -Parameter #{"arg1" = "var1";"arg2" = "var2"}
For Invoke-AzVMRunCommand cmdlet we need to pass the script in the -ScriptPath parameter, so the script file has to be in place from where cmdlet is being run. Wherever you are running the script you will need to have the script available there.
Limitation:
To Run this command the below permission is needed Microsoft.Compute/virtualMachines/runCommand/action .
The Virtual Machine Contributor role and higher levels will have this.
Whereas,
Invoke-command cmdlet is just used to invoke any RestAPI or an action using the PowerShell.
Refer this document to know about the Invoke command.

Job Suspended Run Login-AzureRmAccount to login using Azure AutomationAccounts System Managed Identity

I am trying to shutdown the VM using Azure Automation Account System Managed identity option.
However I am ending up with below error.
As per the other articles it is mentioned to upgrade the module Update-ModulesInAutomationToLatestVersion but I could not update due to below error. I am not sure what is the issue in the script. Same script works with AzureRunAsConnection option without issues ( script ).I even checked with simple login with System Managed Identity it successfully login and fetches the resource group names.
I have tested the above shared script in my automation account. Below are
the couple of observations:
You need to use Connect-AzureRMAccount -Identity cmdlet instead of 'connect-AzAccount` to connect to your subscription because the rest of the script that you have written using Azure RM cmdlets.
If we use AzureRM cmdlets in your run book script the job is getting suspended stating that Azure RM is going to retired and suggesting us to use Az Module in your workflow.
You can refer to this documentation on how to migrate your PowerShell scripts automatically from AzureRM to AZ modules.
If you want to perform start/stop on your virtual Machines you can leverage the Azure Automation start/stop during the off hours feature.
According to the MICROSOFT DOCUMENTATION and looking at your script the Azure Rm module is not supported and it has been updated to the latest version of Az module.
For more information please refer the below links:-
MICROSOFT DOCUMENT|Using a system-assigned managed identity for an Azure Automation account & Troubleshoot runbook issue.

PowerShell to turn on All network by Azure pipelines

I wrote a power-shell and it is running fine from the windows machine by PS editor. System prompt for my user name to authenticate before running this.
$subscription = "dev"
Connect-AzAccount -Subscription $subscription
$keyvaultname = "kv-dev"
Update-AzKeyVaultNetworkRuleSet -DefaultAction Allow -VaultName $keyvaultname
when I am running the same script in Azure pipelines (using PowerShell task) it is throwing following error. I removed the Connect-AzAccount.
Update-AzKeyVaultNetworkRuleSet' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
How can I run this from azure pipelines using Power Shell task.
To execute the Azure PowerShell commands in pipeline job to manage Azure resources, you should use the Azure PowerShell task instead of PowerShell task.
You need to set up an Azure Resource Manager service connection (ARM connection) for use on the Azure PowerShell task. This ARM connection is used as the authentication, and you should not directly set the authentication in the PowerShell scripts.

Scheduling Azure Virtual Machine (VM) Startup with Tags

I am trying to put some auto start policy on my VM on Azure.
So, I used automation account and power shell script to do this from this link: https://adamtheautomator.com/azure-vm-schedule/
But on testing it give me error of Run Login-AzureRmAccount to login
Please suggest how to fix this?
## Get the Azure Automation Acount Information
$azConn = Get-AutomationConnection -Name 'AzureRunAsConnection'
## Add the automation account context to the session
Add-AzureRMAccount -ServicePrincipal -Tenant $azConn.TenantID -ApplicationId $azConn.ApplicationId -CertificateThumbprint $azConn.CertificateThumbprint
## Get the Azure VMs with tags matching the value '10am'
$azVMs = Get-AzureRMVM | Where-Object {$_.Tags.StartTime -eq '10am'}
## Start VMs
$azVMS | Start-AzureRMVM
Regards
ESNGSRJ
This can happen when the Run As account isn't configured appropriately. You will need to create one to provide authentication for managing resources on the Azure Resource Manager using Automation runbooks.
When you create a Run As account, it performs the following tasks:
Creates an Azure AD application with a self-signed certificate, creates a service principal account for the application in Azure AD, and assigns the Contributor role for the account in your current subscription.
Creates an Automation certificate asset named AzureRunAsCertificate in the specified Automation account.
Creates an Automation connection asset named AzureRunAsConnection in the specified Automation account.
Please note the following requirements from the referenced link:
You must have an Azure Automation Account with an Azure Run As account already prepared. If you don’t have this yet, learn how to create one when you go to Create a new Automation account in the Azure portal.
The Azure PowerShell module must be installed. If you don’t have this yet, please go to the Install the Azure PowerShell module page for more information.
Note: You can configure your Runbook to use managed identities as well and it has added benefits as compared to using Run As accounts. You can get started with this tutorial to use managed identity.

Resources