Azure runbook powershell script to copy all webapp settings - powershell

I am trying to run the following script as a runbook to copy all settings from one webapp to another but I get the following error.
try
{
$acct = Get-AzureRmSubscription
}
catch
{
Login-AzureRmAccount
}
$fromResourceGroup = 'resourceG1'
$fromSite = 'website1'
$toResourceGroup = 'resourceG2'
$toSite = 'website2'
$props = (Invoke-AzureRmResourceAction -ResourceGroupName $fromResourceGroup -ResourceType Microsoft.Web/sites/Config -Name $fromSite/appsettings -Action list -ApiVersion 2015-08-01 -Force).Properties
$hash = #{}
$props | Get-Member -MemberType NoteProperty | % { $hash[$_.Name] = $props.($_.Name) }
Set-AzureRMWebApp -ResourceGroupName $toResourceGroup
-Name $toSite -AppSettings $hash
exception:
Get-Member : You must specify an object for the Get-Member cmdlet.
At line:18 char:10
+ $props | Get-Member -MemberType NoteProperty | % { $hash[$_.Name] = $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-Member], InvalidOperationException
+ FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand
Set-AzureRMWebApp : The term 'Set-AzureRMWebApp' 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.
At line:20 char:1
+ Set-AzureRMWebApp -ResourceGroupName $toResourceGroup
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Set-AzureRMWebApp:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
-Name : The term '-Name' 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.
At line:21 char:9
+ -Name $toSite -AppSettings $hash
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (-Name:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

An Automation Runbook use a different strategy for login, so you should not just copy a PowerShell script to a Runbook and expect it run exactly the same way as you run locally.
You see that the command Login-AzureRmAccount will popup a window asking for user name and password. But, in an Automation Runbook, it can't. Hence, you need to do something else in order to properly login.
Create a new Active Direcotry User for your automation.
a. Log into the Azure Classic Portal.
b. Select Active Directory, and click your default Active Directory.
c. Click User, and click Add User. For Type of User, choose New user in your organization. It cannot be User with an existing Microsoft account, because it will fail when trying to login in a Runbook.
d. On the User Profile, for Roles, a Service administrator is good enough, but if you want, you can choose Global administrator. Do not Enable Multi-Factor Authentication. If you do, again, it will fail when trying to login in a Runbook.
e. Note the user’s full name and temporary password.
f. Back to the Classic Portal, Click Settings > Administrators > Add. Type in the user name you got above, and select your subscription.
g. Log out of Azure and then log back in with the account you just created. You will be prompted to change the user’s password.
Note: If you already have a "non-Microsoft" and MFA-disabled user account, you can skip this step. For more information, see Configuring Azure Automation
Create a PS credential asset for your Runbook.
a. Log into the Azure Portal, and choose your automation.
b. In your automation account setting blade, click Assets > Credential.
c. Click Add a credential, enter Name, User name, and Password (the user name and password you create in the previous step), and click Create.
Instead of simply using Login-AzureRmAccount, you should us the following to login.
$cred = Get-AutomationPSCredential -Name "<your credential name>"
Login-AzureRmAccount -Credential $cred

This error:
Get-Member : You must specify an object for the Get-Member cmdlet.
means that $props is null, since you are passing it to Get-Member. So
$props = (Invoke-AzureRmResourceAction -ResourceGroupName $fromResourceGroup -ResourceType Microsoft.Web/sites/Config -Name $fromSite/appsettings -Action list -ApiVersion 2015-08-01 -Force).Properties
is evaluating to null for some reason.
This is probably because you are not authenticating to Azure correctly. Please see https://azure.microsoft.com/en-us/blog/azure-automation-authenticating-to-azure-using-azure-active-directory/ and https://azure.microsoft.com/en-us/blog/announcing-azure-resource-manager-support-azure-automation-runbooks/ for more info.

Related

Non-Interactive - Get-MgUser : Insufficient privileges to complete the operation

I followed https://www.christianfrohn.dk/2022/04/23/connect-to-microsoft-graph-with-powershell-using-a-certificate-and-an-azure-service-principal/ to connect to Microsoft Graph but I'm getting the following error.
Get-MgUser -Top 1
> Get-MgUser : Insufficient privileges to complete the operation.
> At line:1 char:1
> + Get-MgUser -Top 1
> + ~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidOperation: ({ ConsistencyLe...ndProperty = }: <>f__AnonymousType62`9) [Get-MgUser
> _List1], RestException`1
> + FullyQualifiedErrorId : > Authorization_RequestDenied,Microsoft.Graph.PowerShell.Cmdlets.GetMgUser_List1
From what I can tell I need to consent to the permissions. I found numerous sources for how to do this for interactive sessions but nothing said how to do this for non-interactive sessions.
I tried adding -Scopes to the connection string but got this error
Connect-MgGraph -ClientID [snip] -TenantId [snip] -CertificateThumbprint [snip] -Scopes 'User.Read.All'
> Connect-MgGraph : Parameter set cannot be resolved using the specified named parameters.
> At line:1 char:1
> + Connect-MgGraph -ClientID 19cb80c5-b355-42bc-a892-e73d11f57ef4 -Tenan ...
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidArgument: (:) [Connect-MgGraph], ParameterBindingException
> + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Graph.PowerShell.Authentication.Cmdlets.ConnectMgGraph
How do I do this?
EDIT
This is how I'm connecting
Connect-MgGraph -ClientId $clientId -TenantId $tenantId -CertificateThumbprint $thumbPrint
Welcome To Microsoft Graph!
API Permissions
Thanks
Your App Registration has the incorrect permissions. There are 2 types of permissions, delegated (aka scope), and application (aka role).
Reference: Permission types
For an "interactive" session, your app will be interacting on behalf of the user, therefore uses delegated permissions.
For a "non-interactive" session, your app will be acting as itself, so it needs application type permissions.
When connecting as an application ("non-interactive"), you also don't specify the -Scopes parameter
To identify the permissions needed to run a specific cmdlet of the microsoft.graph module you can use the find-mgGraphCommand cmdlet, e.g.:
(Find-MgGraphCommand -Command get-mguser).permissions
To identify which permissions are assigned to the current session you can use the get-mgcontext cmdlet, e.g.:
(get-mgcontext).scopes
If you run a interactive session you have to specify the scopes, e.g.:
Connect-MgGraph -Scopes user.read.all
To connect in the context of a service principal by using a certificate you can do:
#Get the certificate used as secret from the Windows certificate store
$cert = Get-ChildItem -Path 'Cert:\LocalMachine\MY' | ?{$_.thumbprint -eq $CertificateThumbprint}
#establish connection
connect-mggraph -certificate $cert -tenantid [tenantId] -clientId [clientId]
btw. clientId = objectId of the service principal

powershell returned an error:(403) WebException using New-pnpList

I had my PS script running the other day and created a new list with a single field with no issues. Was able to view the list in the Site Contents lib.
Today, it's not working. I tried running the PS code below and then resorted to running the new-pnplist code at the command line...got the same error which is shown below.
I'm using the Global admin account. Using version 3.13.19 SharePointPNPPowerShellOnline. Executed the commands from Powershell ISE which is what I did the other day when it worked. And, I was able to connect successfully using the Connect-sposervice command.
Error:
new-pnplist -Template GenericList -Title 'TestPNP2'
new-pnplist : The remote server returned an error: (403) Forbidden.
At line:1 char:1
+ new-pnplist -Template GenericList -Title $ListName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [New-PnPList], WebException
+ FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.Lists.NewList
Code:
$TargetListURL="https://<my sharepoint.com>/sites/CKCDemo"
$ListName="TESTPNP2"
Connect-PnPOnline -url $TargetListURL -CurrentCredentials
New-PnPList -Template GenericList -Title $ListName
Add-PnPField -List $ListName -DisplayName "MyTEST" -InternalName "MyTEST" -Type Text -AddToDefaultView
Get-PnPList`
Make sure you have enough permission to create a list in this site. You could try to go to the site directly, check whether you could create a list through ui.
Note: A global admin will not automatically have access to individual sites unless explicitly granted.

New-AzureRmResourceGroup command not working in powershell

I have logged into my Azure account and selected the appropriate subscription.
But it always gives the same error
PS C:\WINDOWS\system32> New-AzureRmResourceGroup -Name "AzureMediaServicesSample" -Location "East US"
New-AzureRmResourceGroup : Run Login-AzureRmAccount to login.
At line:1 char:1
+ New-AzureRmResourceGroup -Name "AzureMediaServicesSample" -Location " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-AzureRmResourceGroup], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzur
eResourceGroupCmdlet
I have selected the subscription too using select-azuresubscription
select-azuresubscription is used for ASM mode.
For ARM mode, you need use Get-AzureRmSubscription -SubscriptionName "your sub" | Select-AzureRmSubscription to select your subscription.
More information please refer to this example.
Update:
You could use the following cmdlet to check Azure PowerShell version.
Get-Module -ListAvailable -Name Azure -Refresh
You could install the latest PowerShell from the link.
I had the same problem and I solved it by changing the environment setting from Bash to Powershell in the upper left corner of the Cloud Shell Window.

Azure Powershell - Switch-AzureMode error in version 1

Hello I am not powershell programmer and I learning right now using pluralsight and exericese file giving me error and I think it happening because or version change of Azure Powershell from 0.9.8 to version 1.0
Here is error :
c:\Pluralsight\chef\2-chef> .\Create-CourseEnvironmentARM.ps1
Switch-AzureMode : The term 'Switch-AzureMode' 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.
At C:\Pluralsight\chef\2-chef\Create-CourseEnvironmentARM.ps1:28 char:1
+ Switch-AzureMode AzureResourceManager -Verbose
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Switch-AzureMode:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Test-AzureResourceGroup : The term 'Test-AzureResourceGroup' 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.
At C:\Pluralsight\chef\2-chef\Create-CourseEnvironmentARM.ps1:32 char:5
+ if((Test-AzureResourceGroup -ResourceGroupName $GroupName) -eq $false){
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-AzureResourceGroup:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
New-AzureResourceGroupDeployment : The term 'New-AzureResourceGroupDeployment' 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.
At C:\Pluralsight\chef\2-chef\Create-CourseEnvironmentARM.ps1:44 char:1
+ New-AzureResourceGroupDeployment `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (New-AzureResourceGroupDeployment:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
File Name :.\Create-CourseEnvironmentARM.ps1
I was searching error in google and confirm that azure power shell
deprecate function "Switch-AzureMode AzureResourceManager -Verbose"
https://github.com/Azure/azure-powershell/wiki/Deprecation-of-Switch-AzureMode-in-Azure-PowerShell
Switch-AzureMode AzureResourceManager -Verbose
Here is code from Create-CourseEnvironmentARM.ps1
Switch-AzureMode AzureResourceManager -Verbose
### Create Resource Group ###
if((Test-AzureResourceGroup -ResourceGroupName $GroupName) -eq $false){
New-AzureResourceGroup -Name $GroupName -Location $Location -Verbose
$ResourceGroup = Get-AzureResourceGroup -Name $GroupName
}
else {$ResourceGroup = Get-AzureResourceGroup -Name $GroupName}
$parameters = #{
'newStorageAccountName'="$StorageName";
'adminUsername'="$AdminUsername";
'dnsNameForPublicIP'="$PublicDNSName"
}
New-AzureResourceGroupDeployment `
-Name $DeploymentName `
-ResourceGroupName $ResourceGroup.ResourceGroupName `
-TemplateFile azuredeploy.json `
-TemplateParameterObject $parameters `
-Verbose
Please help me to correct this code. I think author is never update course and I am in middle of course. I hope someone help me to fix this problem.
There is no more "Switch-AzureMode" since v. 1.0.0 of the Powershell.
The ARM and ASM cmdlets exists together and live together. The ASM cmdlets are with unchanged names, but the ARM cmdlets are all now with RM in their name. Like:
Add-AzureRmAccount
Both the powershell cmdlets can be installed via Web Platform Installer.
More, when on Windows 10, the ARM cmdlets can be installed via PowerShell Gallery using the ofllowing commands (under Aministrative PowerShell console):
Install-Module AzureRM
Confirm all the questions being asked. Then run the
Install-AzureRM
Then you are done with the ARM module. Just make sure that your local execution policy is at least "RemoteSigned".
At the end, you will have to edit all your PowerShell scripts to match the new cmdlets and their parameters. Like the New-AzureResourceGroup is now New-AzureRmResourceGroup: https://msdn.microsoft.com/en-us/library/mt603739.aspx

New-AzureQuickVM not creating VM on exsisting Cloud Service?

I'm trying to run the following Azure Powershell cmdlet to provision a new Virtual Machine on a existing Cloud Service.
PS C:\> Get-AzureService | ft ServiceName
ServiceName
-----------
$AZURETEST-EUWEST0
$AZURETEST-JPWEST0
$AZURETEST-USEAST0
$AZURETEST-USWEST0
PS C:\> $image = "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-201505.01-en.us-127GB.vhd"
PS C:\> New-AzureQuickVM -Windows -ServiceName "$AZURETEST-USEAST0" -name "AZURESVM-USE1" -ImageName $image -Password Password1 -AdminUsername admin -WaitForBoot
New-AzureQuickVM : ResourceNotFound: The deployment name '$AZURETEST-USEAST0' does not exist.
At line:1 char:1
+ New-AzureQuickVM -Windows -ServiceName "$AZURETEST-USEAST0" -name "AZURESVM-USE1" -Im ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureQuickVM], CloudException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.PersistentVMs.NewQuickVM
New-AzureQuickVM : Sequence contains no matching element
At line:1 char:1
+ New-AzureQuickVM -Windows -ServiceName "$AZURETEST-USEAST0" -name "AZURESVM-USE1" -Im ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureQuickVM], InvalidOperationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.PersistentVMs.NewQuickVM
PS C:\>
What doesn't make sense is I'm getting an error that says my Cloud Service - or Deployment Name doesn't exist when you can clearly see it returned when I listed all the available Cloud Services!
First of all, admin as administrator account name will not work. It's a reserved word, once you get past the service name, it will break on this one.
Second, there's nothing wrong with your powershell command and I tested exactly with the same parameters to make sure. I can bet it's the "$" you used for the cloud service name that is being misinterpreted by the cmdlet.
Since you can't rename cloud services, create a new one without the "$" and try again to see if it works.
Update: This is what happens when i try to create CS from the portal with the "$" as first character:
"This field can contain only letters, numbers, and hyphens. The first
and last character in the field must be a letter or number.
Trademarks, reserved words, and offensive words are not allowed."
Try to enter all parameters inline without using named parameters (e.g $image). that solved it for me.
Here is a working example:
$image = "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-Datacenter-20160229-en.us-127GB.vhd"
$location = 'West Europe'
New-AzureQuickVM -Windows -Location $location -ServiceName "RamiSOTest1-cs" -name "RamiSOTest1-VM" -ImageName $image -Password 'RamiPass-1' -AdminUsername 'rami' -WaitForBoot