How to set value of -DefaultProfile (of type IAzureContextContainer) in New-AzSqlSyncMember - azure

I am trying to create a powershell script to create azure data sync between 2 azure SQL databases.
My member database is on another subscription.
I need to set -DefaultProfile which is of type on 'New-AzSqlSyncMember' command.
I am not aware of the syntax for setting this parameter.
My current script without -DefaultProfile looks like below:
New-AzSqlSyncMember -ResourceGroupName $resourceGroupName `
-ServerName $serverName `
-DatabaseName $databaseName `
-SyncGroupName $syncGroupName `
-Name $syncMemberName `
-MemberDatabaseType $memberDatabaseType `
-SyncDirection $syncDirection
I want to set the value of the subscription field using powershell like in the image below using powershell:

Possible cross post from https://social.msdn.microsoft.com/Forums/en-US/4ad3dd3e-314a-4442-957f-da77c17ef85b/how-to-set-value-of-defaultprofile-of-type-iazurecontextcontainer-in-newazsqlsyncmember?forum=azurescripting&prof=required
You want to call Connect-AzAccount with the credentials for the account you want to use in the -DefaultProfile parameter and store that in a variable. You can use that variable to set the parameter:
$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId
New-AzSqlSyncMember <params> -DefaultContext $DefaultProfile
If this throws a type error that it can't convert from a PSAzureContext to a IAzureContextContainer there is an explicit converter available.
$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId
$Converter = New-Object -TypeName Microsoft.Azure.Commands.Profile.Models.AzureContextConverter
$Container = $converter.ConvertFrom($DefaultProfile, [Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer], $null, $true)
New-AzSqlSyncMember <params> -DefaultContext $Container

Related

Query ObjectId of ConditionalAccessLocationCondition

I am writing a script to write to Azure, I basically want to find a user, create a network location, create a conditional access policy. This is what I have so far. The trouble is that the $secmon_guid and $location_policy_guid do not work. If I manually put the values in, it works.
# Run these commands first to connect and install without the #
Install-Module -Name AzureAD -AllowClobber -Force # Answer Y to install NuGet. Run once on workstation running script.
Install-Module -Name Microsoft.Graph.Identity.SignIns -Force # Install this to allow us to setup a trusted location. Run once on workstation running script.
Install-Module MSOnline -Force #Allow us to edit users. Run once on workstation running script.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine #Set execution policy to allow our script to do things.
Import-Module -Name AzureAD #The following 3 commands are ran for each client.
Connect-AzureAD # Use GA credentials from Glue
Connect-MsolService #Reauthenticate if necessary.
Get-AzureADMSConditionalAccessPolicy #This will list out all of the existing CA policies. This is a good opportunity to get them into documentation.
Connect-MgGraph #This enabled graph, you will need to approve the request in the popup window.
#Set variable for account name
Set-Variable -name "account" -Value "secmon"
#Create named location for the IP address
$ipRanges = New-Object -TypeName Microsoft.Open.MSGraph.Model.IpRange
$ipRanges.cidrAddress = "IP ADDR"
New-AzureADMSNamedLocationPolicy -OdataType "#microsoft.graph.ipNamedLocation" -DisplayName "Blackpoint IP Address for SecMon" -IsTrusted $true -IpRanges $ipRanges
#Disable MFA for secmon
Get-MsolUser -SearchString "secmon" | Set-MsolUser -StrongAuthenticationRequirements #()
#Get the Azure AD GUID for use later
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select ObjectID
#Name the policy
$name = "Allow Secmon Only from Blackpoint IP"
#Enable the policy. Set to Disabled to test.
$state = "Enabled"
#Get location GUID and save to variable
$location_policy_guid = Get-AzureADMSNamedLocationPolicy | Where-Object -Property DisplayName -Contains 'Blackpoint IP Address for SecMon' | Select-Object -Property Id
#Working on this
#Create the overarching condition set for CA, this is the container.
$conditions = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessConditionSet
#Include all applications - This might be able to be removed?
$conditions.Applications = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessApplicationCondition
$conditions.Applications.IncludeApplications = 'All'
#Create the user condition and include secmon
$conditions.Users = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessUserCondition
$conditions.Users.IncludeUsers = $secmon_guid
#Add new location policy to CA policy
$conditions.Locations = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessLocationCondition
$conditions.Locations.IncludeLocations = $location_policy_guid
#Grant access control to CA policy
$controls = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessGrantControls
$controls._Operator = "OR"
$controls.BuiltInControls = "block"
#End work
New-AzureADMSConditionalAccessPolicy `
-DisplayName $name `
-State $state `
-Conditions $conditions `
-GrantControls $controls
The error I get is due to poorly formatted GUID's, the values I am pulling are not correct. How can I fix this? Any help is greatly appreciated!
New-AzureADMSConditionalAccessPolicy : Error occurred while executing NewAzureADMSConditionalAccessPolicy
Code: BadRequest
Message: 1054: Invalid location value: #{Id=1234GUID}.
InnerError:
RequestId: 5678GUID
Where you define the variables, you need to use -ExpandProperty on the select-object statement e.g:
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select -ExpandProperty ObjectID
Otherwise, you would have to access your current variable like so:
$conditions.Users.IncludeUsers = $secmon_guid.ObjectID

use Invoke-AzVMRunCommand -Params

I am trying to use the command like so:
a = 345
name = "myVM"
Invoke-AzVMRunCommand -ResourceGroupName $RGName -Name $VMName -CommandId 'RunPowerShellScript' -ScriptPath $FileName -Parameter #{"b" = "a"; "test" = "name"}
the script in the file isn't really important I am just trying to use params inside of it with values of params from the outside. If I put "b" = 345 it works but with the outside param (a), it doesn't so I wanted to know how to do it.
it does execute the script but ignores the commands using these params.
for reference the script is something like this:
New-Item -Path "." -Name "index.html" -ItemType "file" -Value $b
New-Item -Path "." -Name $test -ItemType "file" -Value "3333333"
We use Invoke-AzVMRunCommand to Invoke a run command on the VM. And the -Parameter is used to run the command parameter.
The the type for -Parameter is Hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.
Invoke command is more like a batch script, so when we want to pass a pre-defined variable we have to use the $ symbol without any double quotes (""). So you can solve your problem by following the code snippet below.
#Example
a = 345
name = "myVM"
Invoke-AzVMRunCommand -ResourceGroupName $RGName -Name $VMName -CommandId 'RunPowerShellScript' -ScriptPath $FileName -Parameter #{"b" = $a; "test" = $name}
Read this Invoke-AzVMRunCommand document and about_Hash_Tables document for more information.
Invoke-AzVMRunCommand -ResourceGroupName $RGName -Name $VMName -CommandId 'RunPowerShellScript' -ScriptPath $FileName -Parameter #{"b" = $a; "test" = $name}
It don't work. The same problem.
I have the script which create VM in azure:
$password = ConvertTo-SecureString -String "Qwerty123456" -AsPlainText
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $password
$x = Get-Random 10000 -Minimum 10
$location = "East US"
$rgname = "testVM"+$x
$VMName = "vm1"
# Create Resource group
New-AzResourceGroup -name $rgname -Location $location
# Create VM, vnet, publicIP, port 3389
New-AzVM -ResourceGroupName $rgname `
-Location $location `
-Name "verdyshtest" `
-VirtualNetworkName "virtnet" `
-SubnetName 'verdyshnetwork' `
-PublicIpAddressName "verdyshpublicIP" `
-Image Win2019Datacenter `
-OpenPorts 3389 `
-Credential $cred
# Script only running after deploy
Invoke-AzVMRunCommand -ResourceGroupName $rgname -VMName $VMName -CommandId RunPowerShellScript -ScriptPath '.\2 Install app on VM.ps1'
In last count it can't to execute 'invoke-azvmruncommand', because of variable in parameters.
But in New-AzVM cmdlet variables works well.
Had a error:
error

Azure ARM template script error when creating certificate for apex domain

Really scratching my head on this one, I keep getting the error below:
New-AzureRmResourceGroupDeployment : A parameter cannot be found that matches parameter name 'SubjectName'.
At azure_cli_-_create_cert.ps1:12 char:80
for the Azure ARM template script below:
$subscription = ""
$resourceGroupName = ""
$appServicePlanName = ""
$subjectName = ""
Set-AzureRmContext -SubscriptionId $subscription
$appServicePlan = Get-AzureRmResource `
| Where-Object {$_.ResourceGroupName -eq $resourceGroupName} `
| Where-Object {$_.Name -eq $appServicePlanName}
New-AzureRMResourceGroupDeployment -ResourceGroupName $resourceGroupName -SubjectName $subjectName -AppServicePlanName $appServicePlanName -Location $appServicePlan.Location -TemplateFile "CreateHttpFreeCert.json"
Does anyone know why this is?
I am running the script in a windows powershell script (i.e. .ps1 script).
It seems like you need to supply the parameters for your template in as a JSON file using -TemplateParameterFile or -TemplateParameterObject
https://learn.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermresourcegroupdeployment?view=azurermps-6.13.0#example-1--use-a-custom-template-and-parameter-file-to-create-a-deployment

The Azure PowerShell session has not been properly initialized. Please import the module and try again

I'm writing my first powershell script to load data from a CSV to an Azure Storage table. I'm not sure why the line
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName)[0].Value
is throwing an error:
Running Get-Module gives this result:
This is a snippet of the code that I have written till now:
# Step 1, Set variables
# Enter Table Storage location data
$resourceGroupName = "ComputeTesting"
$storageAccountName = 'computetestingdiag'
$tableName = 'strtable'
$dateTime = get-date
# Step 2, Login to your Azure subscription
$sub = Get-AzSubscription -ErrorAction SilentlyContinue
if(-not($sub))
{
Connect-AzAccount
}
# If you have multiple subscriptions, set the one to use
# Select-AzSubscription -SubscriptionId "<SUBSCRIPTIONID>"
# Step 3, Get the access key for the Azure Storage account
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName)[0].Value
# Step 4, Connect to Azure Table Storage
$storageCtx = New-AzureStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
$table = Get-AzureStorageTable -Name $tableName -Context $storageCtx
I checked some of the similar questions and what I understand that uninstalling and re-installing the Azure modules might help. Although I didn't try this yet, is there any other workaround for this? Any help whatsoever would be highly helpful.
According to the script you provided, you use the Az and AzureRM modules at the same PowerShell session. It may cause conflicts. I suggest you use the one module in one session.
For example
$resourceGroupName = "<>"
$storageAccountName = '<>'
$tableName = '<>'
Connect-AzAccount
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName)[0].Value
$storageCtx = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
$table = Get-AzStorageTable -Name $tableName -Context $storageCtx
For more details about how to manage Azure table storage, please refer to the document

Auto sql of azure SQL based on DTU consumption alert

I have to scale my Azure SQL if DTU utilization is high at any moment and scale down if consumption is low for a certain duration.
I know this can be done by setting alert rule and web hook but looking for some redimate stuff which i can refer and utilize it....
Scale up and down takes time and sometimes it takes more than expected. It usually takes 5-10 minutes but sometimes it takes 25-30 minutes. The busier the database is at the time of the scale, the more time it takes to scale up or down. The size of the database also matters.
Remember also that transactions are rolled back when a scale is in progress.
My suggestion is to use the following query to identify patterns in resource consumption and then automate the scale up and down of the database.
SELECT *
FROM sys.dm_db_resource_stats
ORDER BY end_time
Tabulate that data on hours and days of the week to facilitate the pattern identification. After that use Azure Automation and parts of the following PowerShell to automate the scale up/down of the database. The following PowerShell does all what you want, it monitors DTU usage and then based on consumption triggers a scale process.
# Login-AzureRmAccount
# Set the resource group name and location for your server
$resourcegroupname = "myResourceGroup-$(Get-Random)"
$location = "southcentralus"
# Set an admin login and password for your server
$adminlogin = "ServerAdmin"
$password = "ChangeYourAdminPassword1"
# The logical server name has to be unique in the system
$servername = "server-$(Get-Random)"
# The sample database name
$databasename = "mySampleDatabase"
# The ip address range that you want to allow to access your server
$startip = "0.0.0.0"
$endip = "0.0.0.0"
# Create a new resource group
$resourcegroup = New-AzureRmResourceGroup -Name $resourcegroupname -Location $location
# Create a new server with a system wide unique server name
$server = New-AzureRmSqlServer -ResourceGroupName $resourcegroupname `
-ServerName $servername `
-Location $location `
-SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force))
# Create a server firewall rule that allows access from the specified IP range
$serverfirewallrule = New-AzureRmSqlServerFirewallRule -ResourceGroupName $resourcegroupname `
-ServerName $servername `
-FirewallRuleName "AllowedIPs" -StartIpAddress $startip -EndIpAddress $endip
# Create a blank database with S0 performance level
$database = New-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname `
-ServerName $servername `
-DatabaseName $databasename -RequestedServiceObjectiveName "S0"
# Monitor the DTU consumption on the imported database in 5 minute intervals
$MonitorParameters = #{
ResourceId = "/subscriptions/$($(Get-AzureRMContext).Subscription.Id)/resourceGroups/$resourcegroupname/providers/Microsoft.Sql/servers/$servername/databases/$databasename"
TimeGrain = [TimeSpan]::Parse("00:05:00")
MetricNames = "dtu_consumption_percent"
}
(Get-AzureRmMetric #MonitorParameters -DetailedOutput).MetricValues
# Scale the database performance to Standard S1
$database = Set-AzureRmSqlDatabase -ResourceGroupName $resourcegroupname `
-ServerName $servername `
-DatabaseName $databasename `
-Edition "Standard" `
-RequestedServiceObjectiveName "S1"
# Set an alert rule to automatically monitor DTU in the future
Add-AzureRMMetricAlertRule -ResourceGroup $resourcegroupname `
-Name "MySampleAlertRule" `
-Location $location `
-TargetResourceId "/subscriptions/$($(Get-AzureRMContext).Subscription.Id)/resourceGroups/$resourcegroupname/providers/Microsoft.Sql/servers/$servername/databases/$databasename" `
-MetricName "dtu_consumption_percent" `
-Operator "GreaterThan" `
-Threshold 90 `
-WindowSize $([TimeSpan]::Parse("00:05:00")) `
-TimeAggregationOperator "Average" `
-Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners)
# Clean up deployment
# Remove-AzureRmResourceGroup -ResourceGroupName $resourcegroupname

Resources